带有@RestController 的 Spring 安全性 - JSONish CustomAuthenticationProvider 响应 [英] Spring security with @RestController - JSONish CustomAuthenticationProvider response

查看:26
本文介绍了带有@RestController 的 Spring 安全性 - JSONish CustomAuthenticationProvider 响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我还是 Spring 的新手,尤其是 Spring Security.此应用程序是 Restful 应用程序.

I still new with Spring especially spring security. This application is Restful application.

以下是来自 @RestController 的片段:

Following is snippet from @RestController :

@RequestMapping(value = "/new", method = RequestMethod.POST)
    @PreRegistration("new")
    @ResponseBody
    public ResponseEntity<Void> newUser(@RequestBody @Valid TempUser user, UriComponentsBuilder ucBuilder) {

        registerService.addUser(user);

        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(ucBuilder.path("/register/{userName}").buildAndExpand(user.getUserName()).toUri());
        return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
    }

以下是来自 CustomAuthenticationProvider 的片段:

Following is the snippet from CustomAuthenticationProvider:

@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException  {
    final String name = authentication.getName();
    final String password = authentication.getCredentials().toString();
    if (name.equals("admin") && password.equals("system")) {
        final List<GrantedAuthority> grantedAuths = new ArrayList<>();
        grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
        final UserDetails principal = new User(name, password, grantedAuths);
        final Authentication auth = new UsernamePasswordAuthenticationToken(principal, password, grantedAuths);
        return auth;
    } 
    else {
        throw new BadCredentialsException("NOT_AUTHORIZED");
    }
}

安全配置:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
            .anyRequest().authenticated()
            .and()
        .requestCache()
            .requestCache(new NullRequestCache())
            .and()
        .httpBasic()
            .and()
        .csrf().disable();
}

我试图实现的是当 CustomAuthenticationProvider 抛出异常时(例如错误的凭据"或需要完整身份验证...",我想自定义响应并返回到响应正文JSON 格式.

What I try to achieve is when the CustomAuthenticationProvider thrown an exception (e.g "bad credential" or "Full authentication required...", I want to customize the response and return to the Response Body in JSON format.

我所做的是创建一个新的异常并使用 AOP 调用它.但它似乎不起作用.我也尝试使用 @ControllerAdvice,但似乎效果不佳,因为 CustomAuthenticationProvider 在控制器之外(我猜).

What I have done is to create a new exception and invoke it using AOP. But it seems like not working. I also tried to use @ControllerAdvice, but it seems like not working as well since the CustomAuthenticationProvider is outside the controller (I guess).

推荐答案

对此有更好的方法.您应该在 spring 安全配置和类中添加 authenticationEntryPoint,它实现了 AuthenticationEntryPoint 接口.像这样:

There is a better way for this. You should add authenticationEntryPoint in spring security config and class, which implements AuthenticationEntryPoint interface. Something like this:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
            .antMatchers("/login").permitAll()
            .anyRequest().authenticated()
            .and()
        .requestCache()
            .requestCache(new NullRequestCache())
            .and()
        .httpBasic()
        // --> begin change: new lines added
            .and()
        .exceptionHandling().authenticationEntryPoint(new AuthExceptionEntryPoint())
        // <-- end change
            .and()
        .csrf().disable();

}

AuthExceptionEntryPoint 类,用于生成 JSON Jackson ObjectMapper 使用:

AuthExceptionEntryPoint class, for producing JSON Jackson ObjectMapper used:

public class AuthExceptionEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, 
                         AuthenticationException authException) 
                         throws IOException, ServletException {

        List<String> errors = new ArrayList<>();
        errors.add("Unauthorized");
        response.setContentType("application/json");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.writeValue(response.getOutputStream(), errors);
        } catch (Exception e) {
            throw new ServletException();
        }
    }
}

您可以在 Spring 文档

这篇关于带有@RestController 的 Spring 安全性 - JSONish CustomAuthenticationProvider 响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆