当JWT无效时自定义来自REST的响应

时间:2018-08-03 02:59:13

标签: spring rest spring-security

当标头中的授权承载 function getAll() { $scope.urls = data; $scope.loading = false; } function init() { $scope.loading = true; getAll(); } 无效时,我的REST应用正在尝试自定义响应。我期望能够在我的<JWT>的暗示中做到这一点。但是,当我的AuthenticationEntryPoint中的JWT验证抛出AuthenticationProvider AuthenticationException时,不会被调用。如果标题中完全缺少授权,则此方法有效。但这不适用于错误的令牌本身。我想念什么?

ResourceServerConfigurerAdapter

AuthenticationEntryPoint.commence

AuthenticationEntryPoint

@EnableResourceServer
@EnableWebSecurity
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    @Value("${jwt.expectedAudience}")
    private String expectedAudience;
    @Value("${jwt.expectedIssuer}")
    private String expectedIssuer;
    @Value("${jwt.expectedSubject}")
    private String expectedSubject;
    @Value("${jwt.jwksEndpoint}")
    private String jwksEndpoint;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/api").authenticated();
        http.csrf().disable().exceptionHandling().authenticationEntryPoint(new RestAuthenticationEntryPoint());
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        JwtValidator validator = new JwtValidatorJose4j(new HttpsJwks(jwksEndpoint), expectedAudience, expectedIssuer, expectedSubject);
        resources.authenticationManager(new ProviderManager(Arrays.asList(new OAuth2AuthenticationProvider(validator))));
    }
}

AuthenticationProvider

public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {
    private static final long serialVersionUID = 1L;

    @Override
    public void commence(HttpServletRequest req, HttpServletResponse res, AuthenticationException e) throws IOException, ServletException {
        res.setStatus(401); 
        res.setHeader("Content-Type", "application/json");
        res.getWriter().write("My custom response");
    } 
}
  • Spring Boot 2.0.2.RELEASE
  • spring-security-oauth2 2.3.3。发布

0 个答案:

没有答案