如何发送注释@CurrentUser的未经授权的响应

时间:2019-03-17 18:38:58

标签: java spring spring-security

如何发送未经授权的注释@CurrentUser响应 我有注释

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface CurrentUser {
    boolean required() default true;
}

具有参数解析器

public class CurrentUserIdMethodArgumentResolver extends AbstractCurrentUserMethodArgumentResolver<CurrentUserId> {
    public CurrentUserIdMethodArgumentResolver() {
        super(CurrentUserId.class, null);
    }

    @Override
    protected boolean isRequired(CurrentUserId annotation) {
        return annotation.required();
    }

    @Override
    protected Object resolveName(String name, MethodParameter parameter, NativeWebRequest request) throws Exception {
        return (getCurrentUser() != null)? getCurrentUser().getId() : null;
    }
}

配置Spring Security

  @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                            .antMatchers(REACT_API_PERMITTED_URL, PERMITTED_SOCKET_PUBLIC_TOPIC, PERMITTED_SOCKET_ENDPOINT1, PERMITTED_SOCKET_ENDPOINT2).permitAll()
                            .antMatchers(SOCKET_PRIVATE_ENDPOINT, NOT_PERMITTED_SOCKET_ENDPOINT1, NOT_PERMITTED_SOCKET_ENDPOINT2).authenticated()
                            .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
                            .antMatchers("/moderator/**").access("hasRole('ROLE_MODERATOR')")
                            .anyRequest().authenticated()
                .and().headers()
                        .frameOptions().sameOrigin()
                .and().formLogin()
                        .loginPage(REACT_API_USER_LOGIN)
                        .permitAll()
                             .successHandler(successHandler)
                             .failureHandler(failureHandler)

                        .and().csrf().disable()
                .addFilterAfter(userFilter, LogoutFilter.class)
                .addFilterAfter(adminConfirmFilter, SwitchUserFilter.class)

                .logout()
                    .logoutUrl(REACT_API_USER_LOGOUT)
                    .logoutSuccessUrl(REACT_API)
                    .logoutSuccessHandler(defaultLogoutHandler)
                    .invalidateHttpSession(true)
                .permitAll();
    }

如果用户未被授权,我想在控制器中返回HTTP.STATUS.unauthorized调用

 @GetMapping("/test")
 public User test(@CurrentUser User current) {
return current
}

现在我的状态为400,错误请求,但想配置此状态

2 个答案:

答案 0 :(得分:0)

Spring已经具备了这一功能,只需将@EnableGlobalMethodSecurity(prePostEnabled = true)添加到您的配置中,并使用特殊注释@PreAuthorize("isAuthenticated()")@PreAuthorize("hasAnyRole('ADMIN)")等为您的安全方法添加注释:

@EnableGlobalMethodSecurity(prePostEnabled = true)
@Configuration
public class WebSecurityConf43547 extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
    ....
    }
}

并在您的控制器中

@GetMapping("/test")
@PreAuthorize("isAuthenticated()") //this annotation better add to service method @Service
public String test() {
    return "abc"
}

或     导入org.springframework.security.core.Authentication;

@GetMapping("/test")
public String getOk(Authentication authentication) {
   return authentication.getName();
}

答案 1 :(得分:0)

我决定是这样的问题:

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

    @Bean
    public CurrentUserMethodArgumentResolver userMethodArgumentResolver() {
        return new CurrentUserMethodArgumentResolver() {
            @Override
            protected Object resolveName(String name, MethodParameter parameter, NativeWebRequest request) throws Exception {
                SecurityContext securityContext = SecurityContextHolder.getContext();
                CurrentUser annotation = parameter.getParameterAnnotation(CurrentUser.class);
                boolean anonymousUser = securityContext.getAuthentication() instanceof AnonymousAuthenticationToken;
                if (annotation.required() && anonymousUser) {
                    throw new BadCredentialsException("access is denied");
                }
                return super.resolveName(name, parameter, request);
            }
        };
    }

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> list) {
        list.add(userMethodArgumentResolver());
        super.addArgumentResolvers(list);
}