我创建了两个具有ADMIN和USER角色的用户,但每次尝试登录服务器时都返回403。
Web安全配置:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/admin/**")
.access("hasAnyAuthority('ADMIN','USER')")
.and().formLogin().loginPage("/login").failureUrl("/login?error")
.usernameParameter("username")
.passwordParameter("password")
.and().logout().logoutSuccessUrl("/login?logout")
.and().csrf().disable();
}
my UserService,它将我的用户从db:
@Transactional(readOnly = true)
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userDao.findByUserName(username);
org.springframework.security.core.userdetails.User.UserBuilder builder = null;
if (user != null) {
builder = org.springframework.security.core.userdetails.User.withUsername(username);
builder.disabled(!user.isEnabled());
builder.password(user.getPassword());
String[] authorities = user.getUserRole()
.stream().map(a -> a.getRole()).toArray(String[]::new);
builder.authorities(authorities);
} else {
throw new UsernameNotFoundException("User not found.");
}
return builder.build();
}
csrf被禁用。我还使用hasAnyUthority* 方法,因此不需要ROLE_前缀。我使用spring security 5
我的登录名. html
<head>
<meta charset="utf-8"/>
<link rel="stylesheet" type="text/css" href="resources/style.css"/>
</head>
<body>
<div class="container">
<header>
<h1>Login</h1>
</header>
<div class="alert alert-error" th:if="${error != null}">
<div>
<strong>Okay, Houston, we've had a problem here.</strong>
</div>
</div>
<div class="alert alert-error" th:if="${logout != null}">
<div>
<strong>Okay, Houston, you're logged out successfully .</strong>
</div>
</div>
<form class="form-horizontal" th:action="@{/login}" method="POST">
<fieldset>
<div class="control-group">
<label class="control-label">Login</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on">@</span>
<input id="loginField" name="username" class="span3" type="text"/>
</div>
</div>
</div>
<div class="control-group">
<label class="control-label">Password</label>
<div class="controls">
<input id="passwordField" name="password" class="span3" type="password"/>
</div>
</div>
<div class="form-actions">
<button id="loginButton" class="btn btn-primary" type="submit">Login</button>
</div>
</fieldset>
</form>
</div>
</body>
我在示例项目中做了所有的事情,但它仍然不想让我登录。
2条答案
按热度按时间ohfgkhjo1#
我看不出
hasAnyAuthority(...)
没有“ROLE_"也能正常工作,请尝试.access("hasAnyRole('ADMIN','USER')")
或.access("hasAnyRole('ROLE_ADMIN','ROLE_USER')")
。请注意,在
String[] authorities = user.getUserRole().stream().map(a -> a.getRole()).toArray(String[]::new);
中,您需要在a.getRole()
中返回带有前缀ROLE_
的代码,或者返回与hasAnyAuthority(...)
中相同的代码例如,如果您的
a.getRole()
将返回WHAT_EVER
,则hasAnyAuthority('WHAT_EVER)
应该工作,但hasAnyRole('WHAT_EVER')
将期望a.getRole()
返回ROLE_WHAT_EVER
fquxozlt2#
也许它会帮助一些人,所以我会解开我的问题。我不能登录,因为当我启动我的程序,我添加了一些新的用户没有加密的密码。但Spring的安全解密它无论如何,所以这就是为什么我不能登录,并得到403 repsonse。所有我需要的是加密密码之前,将其添加到数据库。