春季安全与@RestController - JSONish CustomAuthenticationProvider响应 [英] Spring security with @RestController - JSONish CustomAuthenticationProvider response

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

问题描述

我仍然有新的春天尤其是在春季安全。此应用程序是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");
    }
}

SecurityConfig:

SecurityConfig :

@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,但似乎不是控制器(我猜)。

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).

感谢您。

推荐答案

有就是这个更好的方法。你应该在春季安全配置和类,它实现的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 杰克逊 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();
        }
    }
}

有关春季安全配置的更多信息,你可以阅读的春文档

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

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