我正在尝试在Spring Boot应用程序中配置Spring Security,以便只允许某些用户访问某些URL,如果他们有特定的角色,即我在创建用户时存储的用户或管理员角色。我看了几个例子here,几乎可以做我正在寻找的事情。我对Spring的UserDetailsService
界面感到有点困惑,以及在尝试访问UserDetailsService
之类的网址时,我应该如何将用户名从用户传递到localhost:8080/addtour
。目前我的代码如下所示:
@Data
@Scope("session")
public class User {
@Id
private String id;
private String userName;
private String password;
private List<Role> roles;
我的SecurityConfig
课程:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.exceptionHandling()
.accessDeniedPage("/accessdenied")
.and()
.authorizeRequests()
.antMatchers("/resources/**", "/signup", "/search").permitAll()
.antMatchers("/viewtour").hasAnyRole("USER", "ADMIN")
.antMatchers("/addtour").hasAnyRole("ADMIN")
.and()
.logout()
.permitAll()
.logoutSuccessUrl("/index.html");
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(new UserDetailServiceImpl());
}
实施Springs UserDetailServiceImpl
的{{1}}:
UserDetailService
使用Thymeleaf的我的登录页面:
public class UserDetailServiceImpl implements UserDetailsService {
@Autowired
private UserService userService;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
try {
User user = userService.retrieveUserByUserName(username);
if (user == null) {
return null;
}
return new org.springframework.security.core.userdetails.User(user.getUserName(), user.getPassword(), getAuthorities(user));
} catch (Exception e){
throw new UsernameNotFoundException("User not found");
}
}
private Set<GrantedAuthority> getAuthorities(User user){
Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
for (Role role : user.getRoles()) {
GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(role.toString());
authorities.add(grantedAuthority);
}
System.out.println("user authorities are " + authorities.toString());
return authorities;
}
答案 0 :(得分:1)
登录页面中的参数名称有误,请参阅
FormLoginConfigurer#usernameParameter
:
执行身份验证时查找用户名的HTTP参数。默认为&#34;用户名&#34;。
FormLoginConfigurer#passwordParameter
:
执行身份验证时查找密码的HTTP参数。默认为&#34;密码&#34;。
更改登录页面中参数的名称或更改SecurityConfig
中的名称。