gpt4 book ai didi

java - Spring Boot Security 匿名授权

转载 作者:行者123 更新时间:2023-11-30 08:32:01 26 4
gpt4 key购买 nike

出于多种目的我需要使用

SecurityContextHolder.getContext().getAuthentication()

我的 Controller /服务中的方法。

我确实将我的应用程序从 XML 配置的 Spring MVC 应用程序(现在只有 Java 配置)迁移到 Spring Boot 1.4.1,以前使用过类似的方法。

我在调用 SecurityContextHolder.getContext().getAuthentication() 时遇到问题,例如在这个 Controller 中:

@RestController
@Secured("IS_AUTHENTICATED_ANONYMOUSLY")
@RequestMapping("utils")
public class UtilsController {
@RequestMapping(value = "/check_auth", method = RequestMethod.GET)
public Boolean getAuthState() throws SQLException {
if (SecurityContextHolder.getContext().getAuthentication() == null){
logger.info("Auth obj null");
}

if (SecurityContextHolder.getContext().getAuthentication().getName() != null && SecurityContextHolder.getContext().getAuthentication().getName() != "anonymousUser") {
return true;
} else return false;
}
}

它总是返回null。无法弄清楚为什么匿名身份验证不起作用。

这是 Spring Security 配置

    @Override
protected void configure(HttpSecurity http) throws Exception {
http
.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint).and()
.formLogin()
.successHandler(ajaxSuccessHandler)
.failureHandler(ajaxFailureHandler)
.loginProcessingUrl("/authentication")
.passwordParameter("password")
.usernameParameter("username")
.and()
.logout()
.deleteCookies("JSESSIONID")
.invalidateHttpSession(true)
.logoutUrl("/logout")
.logoutSuccessUrl("/")
.and()
.csrf().disable()
// .anonymous().disable()
.authorizeRequests()
// .anyRequest().anonymous()
.antMatchers("/utils").permitAll()
.antMatchers("/oauth/token").permitAll()
.antMatchers("/admin/*").access("hasRole('ROLE_ADMIN')")
.antMatchers("/user/*").access("hasRole('ROLE_USER')");
}

我确实尝试过在 Controller 上使用和不使用 @Secured 注释。

                .authorizeRequests()
// .anyRequest().anonymous()
.antMatchers("/utils").permitAll()

此设置的不同变体。

最佳答案

您将获得 null:

SecurityContextHolder.getContext().getAuthentication()

因为您没有在您的安全配置中进行身份验证。

你可以添加一个简单的:

.authenticated()                                                 
.and()
// ...
.formLogin();

如果您使用表单登录。

现在,在您对每个请求进行身份验证之后,您应该会得到 null 以外的东西。

这是来自 Spring Security 文档的示例:

protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/resources/**", "/signup", "/about").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")
.anyRequest().authenticated()
.and()
// ...
.formLogin();
}

关于java - Spring Boot Security 匿名授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40356150/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com