简体   繁体   中英

how to send an unauthorized response for annotation @CurrentUser

how to send an unauthorized response for annotation @CurrentUser i have annotation

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

have argument resolver

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;
    }
}

configure 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();
    }

I want in my controller return to HTTP.STATUS.unauthorized calling it, if the user is not authorized

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

Now I have status 400, BAD REQUEST, but want configure this status

Spring already have this, just add @EnableGlobalMethodSecurity(prePostEnabled = true) to your configuration and annotate your secured method with special annotation @PreAuthorize("isAuthenticated()") or @PreAuthorize("hasAnyRole('ADMIN)") etc:

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

and in your controller

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

or import org.springframework.security.core.Authentication;

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

I decided to its question so:

@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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM