为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕尼黑8549860 2022-08-17 10:18:29
如何发送未经授权的注释响应@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;    }}配置弹簧安全性  @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()    }我希望在我的控制器中返回到HTTP。STATUS.未经授权调用它(如果用户未获得授权) @GetMapping("/test") public User test(@CurrentUser User current) {return current}现在我有状态400,错误的请求,但想要配置这个状态
查看完整描述

2 回答

?
慕容708150

TA贡献1831条经验 获得超4个赞

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"

}

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


@GetMapping("/test")

public String getOk(Authentication authentication) {

   return authentication.getName();

}


查看完整回答
反对 回复 2022-08-17
?
红糖糍粑

TA贡献1815条经验 获得超6个赞

我决定它的问题,所以:


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

}


查看完整回答
反对 回复 2022-08-17
  • 2 回答
  • 0 关注
  • 84 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信