gpt4 book ai didi

java - Spring security Basic Authentication - 401 Unauthorized with correct credentials

转载 作者:行者123 更新时间:2023-12-05 07:08:00 24 4
gpt4 key购买 nike

这是我的安全配置类,我正在使用 BCryptPasswordEncoder

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{

@Autowired
private UserDetailsService userDetailsService;

@Autowired
private PasswordEncoder encoder;

@Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic()
.and()
.authorizeRequests()
.antMatchers(HttpMethod.POST,"/api/auth/register")
.permitAll()
.antMatchers(HttpMethod.GET,"/api/auth/resources")
.hasAuthority("USER")
.and()
.csrf().disable();

}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(encoder);
}
}

这是我对 UserDetailsS​​ervice 的实现

public class UserDetailsServiceImpl implements UserDetailsService{

@Autowired
private AccountRepository repo;


@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

Account account = repo.findByUsername(username).orElseThrow(() -> new UsernameNotFoundException("No user found for username " + username));
User user =
new User(account.getUsername(), account.getPassword(), true, true, true, true, AuthorityUtils.createAuthorityList(account.getAuthorities()));
return user;
}

}

上面的 POST 方法是我可以提供存储在 MySQL 表中的用户名和密码的地方。

现在,当我可以使用刚刚添加的用户名和密码使用 Postman 调用 GET 方法时,我会收到如下所示的 401 未授权错误

{
"timestamp": "2020-05-23T20:12:10.165+0000",
"status": 401,
"error": "Unauthorized",
"message": "Unauthorized",
"path": "/api/auth/resources"
}

最佳答案

Spring Security 有 ExpressionUrlAuthorizationConfigurer.java,它有如下方法。这里前缀 ROLE_ 有所不同。

  • 对于 hasAuthority()、hasAnyAuthority() 方法,我们需要传递带有前缀 ROLE_ 的权限,即 ROLE_USER

  • 对于hasRole()方法自动添加前缀ROLE_,这样我们就只能将权限名作为USER


private static String hasRole(String role) {
Assert.notNull(role, "role cannot be null");
if (role.startsWith("ROLE_")) {
throw new IllegalArgumentException("role should not start with 'ROLE_' since it is automatically inserted. Got '" + role + "'");
} else {
return "hasRole('ROLE_" + role + "')";
}
}

private static String hasAuthority(String authority) {
return "hasAuthority('" + authority + "')";
}

private static String hasAnyAuthority(String... authorities) {
String anyAuthorities = StringUtils.arrayToDelimitedString(authorities, "','");
return "hasAnyAuthority('" + anyAuthorities + "')";
}

关于java - Spring security Basic Authentication - 401 Unauthorized with correct credentials,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61978157/

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