具有Office 365身份验证的Spring Boot应用程序

时间:2020-05-29 22:31:50

标签: spring azure spring-boot azure-active-directory msal

我正在开发使用Office 365进行身份验证的应用程序(后端的弹簧启动,前端的响应)。但是我想使用自己的用户组和权限。例如,当一个用户第一次访问/ api / auth时,我想从Microsoft图形中检索信息并将其保存到我的数据库中,然后使用自己的角色/权限保护我的端点。

到目前为止,我设法做到了:

  1. 当我转到localhost:8080(返回)时,我将重定向到Azure门户进行身份验证。然后,我可以访问我的端点
  2. 我可以用自己的角色保护端点
  3. 当我进入localhost:3000(反应应用程序)时,我有一个按钮可以将我重定向到门户并给我一个蓝色访问令牌(感谢MSAL.js)

所以我的问题是我无法在后端验证此蔚蓝令牌并无法从后端向前端发送新令牌来发送请求(例如GET / api / users或POST / api / todos)。我认为后端的配置和实现是错误的,但是我没有找到一种方法来验证令牌并为后端返回令牌...

我希望我很清楚,英语不是我的母语

这是我的WebSecurityConfig

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests().antMatchers("/**")
                .authenticated()
                .and()
                .csrf().csrfTokenRepository(csrfTokenRepository()).and()
                .addFilterAfter(csrfHeaderFilter(), CsrfFilter.class)
                .oauth2Login();

    }

    private Filter csrfHeaderFilter() {
        return new OncePerRequestFilter() {
            @Override
            protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
                CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
                if (csrf != null) {
                    Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
                    String token = csrf.getToken();
                    if (cookie == null || token != null && !token.equals(cookie.getValue())) {
                        cookie = new Cookie("XSRF-TOKEN", token);
                        cookie.setPath("/");
                        response.addCookie(cookie);
                    }
                }
                filterChain.doFilter(request, response);
            }
        };
    }

    @Bean
    public HttpFirewall allowUrlEncodedSlashHttpFirewall() {
        StrictHttpFirewall firewall = new StrictHttpFirewall();
        firewall.setAllowUrlEncodedSlash(true);
        return firewall;
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
        web.httpFirewall(allowUrlEncodedSlashHttpFirewall());
    }

    private CsrfTokenRepository csrfTokenRepository() {
        HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
        repository.setHeaderName("X-XSRF-TOKEN");
        return repository;
    }
}

这就是我保护端点的方法:

@PreAuthorize("hasPermission(#foo, 'write')")

配置文件:

@Configuration
public class AclPermissionEvaluator implements PermissionEvaluator {
    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private SecurityService securityService;

    @Override
    public boolean hasPermission(final Authentication authentication, final Object privilegeName, final Object privilegeType) {
        DefaultOidcUser principal = (DefaultOidcUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Map<String, Object> userAttributes = principal.getAttributes();
        UserInfo userInfo = securityService.getUserInfoByLogin((String) userAttributes.get("unique_name"));
        if (userInfo == null || StringUtils.isBlank((CharSequence) privilegeName) || StringUtils.isBlank((CharSequence) privilegeType)) {
            return false;
        }

        for (Permission permission : roleRepository.getByName(userInfo.getRoleName()).getPermissions()) {
            if (permission.getPermission().startsWith((String) privilegeName) || permission.getPermission().equals("*")) {
                return true;
            }
        }

        return false;
    }

    //We don't need an implementation of this function for now
    @Override
    public boolean hasPermission(final Authentication authentication, final Serializable serializable, final String s, final Object o) {
        return false;
    }

}

安全服务:

@Service
@Transactional
public class SecurityServiceImpl implements SecurityService {
  @Autowired private UserRepository userRepo;

  @Autowired
  private RoleRepository roleRepository;

  @Override
  public UserInfo getUserInfoByLogin(String username) {
    User user = userRepo.getUserByUsername(username);
    ModelMapper modelMapper = new ModelMapper();
    return modelMapper.map(user, UserInfo.class);
  }
}

RoleRepository:

@Repository
public interface RoleRepository extends JpaRepository<Role, Long> {
    public Role getByName(String name);
}

在我的application.yml上:

spring:
  security:
    oauth2:
      client:
        registration:
          azure:
            clientId: <my-clientId>
            clientSecret: <my-secret>

azure:
  activedirectory:
    tenant-id: <my-tenant-id>
    user-group:
      allowed-groups: all
    active-directory-groups: all

1 个答案:

答案 0 :(得分:0)

您可以使用类似于下面的代码

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
@Import(SecurityProblemSupport.class)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    private final CorsFilter corsFilter;
    private final SecurityProblemSupport problemSupport;
    private final OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService;

    public SecurityConfiguration(CorsFilter corsFilter, SecurityProblemSupport problemSupport, OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService) {
        this.corsFilter = corsFilter;
        this.problemSupport = problemSupport;
        this.oidcUserService = oidcUserService;
    }

    @Override
    public void configure(WebSecurity web) {
        web.ignoring()
            .antMatchers(HttpMethod.OPTIONS, "/**")
            .antMatchers("/app/**/*.{js,html}")
            .antMatchers("/i18n/**")
            .antMatchers("/content/**")
            .antMatchers("/swagger-ui/index.html")
            .antMatchers("/test/**");
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http
            .csrf()
            .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
            .and()
            .addFilterBefore(corsFilter, CsrfFilter.class)
            .exceptionHandling()
            .accessDeniedHandler(problemSupport)
            .and()
            .headers()
            .contentSecurityPolicy("default-src 'self'; frame-src 'self' data:; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://storage.googleapis.com; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:")
            .and()
            .referrerPolicy(ReferrerPolicyHeaderWriter.ReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN)
            .and()
            .featurePolicy("geolocation 'none'; midi 'none'; sync-xhr 'none'; microphone 'none'; camera 'none'; magnetometer 'none'; gyroscope 'none'; speaker 'none'; fullscreen 'self'; payment 'none'")
            .and()
            .frameOptions()
            .deny()
            .and()
            .authorizeRequests()
            .antMatchers("/api/auth-info").permitAll()
            .antMatchers("/api/**").authenticated()
            .antMatchers("/management/health").permitAll()
            .antMatchers("/management/info").permitAll()
            .antMatchers("/management/prometheus").permitAll()
            .antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN)
            .and()
            .oauth2Login()
            .userInfoEndpoint()
            .oidcUserService(oidcUserService);
        // @formatter:on
    }

    /**
     * Map authorities from "groups" or "roles" claim in ID Token.
     *
     * @return a {@link GrantedAuthoritiesMapper} that maps groups from
     * the IdP to Spring Security Authorities.
     */
    @Bean
    public GrantedAuthoritiesMapper userAuthoritiesMapper() {
        return (authorities) -> {
            Set<GrantedAuthority> mappedAuthorities = new HashSet<>();

            authorities.forEach(authority -> {
                mappedAuthorities.addAll(authorities);
            });
            return mappedAuthorities;
        };
    }

}

您需要更改userAuthoritiesMapper方法以实现所需的目标

额外配置

spring安全配置

spring:
  security:
    oauth2:
      client:
        registration:
          azure:
            client-id: <<CLIENT_ID>>
            client-secret: <<CLIENT_SECRET>>

Azur Active Directory配置

azure:
  activedirectory:
    tenant-id: <<YOUR_TENANT_ID>>
    active-directory-groups: Users
  b2c:
    reply-url: http://localhost:9000 # should be absolute url.
    logout-success-url: http://localhost:9000

每当您陷入任何弹簧启动配置时,我都会给您一个秘密,以了解如何jhipster做到

您可以通过访问jhipster创建者发布的article来找到更多信息

注意:SecurityProblemSupport是由zalando实现的库 最后发布的代码是从此repo

复制的