Spring安全角色访问,登录
我在实现spring安全性时遇到了一些问题,特别是用户和管理员角色。我希望每个角色类型重定向到其各自的页面/用户和/管理员。我已经阅读了无数的教程,每一个似乎都有点不同于上一个,这一切都非常混乱。我想知道是否有人能定义我需要做什么,因为我不认为我离我目前所做的事情太远了。目前的问题是,它没有像我登录后试图检索Prinicipal.getName()时那样重定向,我不认为它是在创建会话,因为它总是空的。除了这个我还缺什么吗?非常感谢您的帮助 几乎整个应用程序都包括注册功能、userRepo和视图 公共类UserDetailService实现UserDetailsService{Spring安全角色访问,登录,spring,spring-mvc,spring-security,spring-data-jpa,Spring,Spring Mvc,Spring Security,Spring Data Jpa,我在实现spring安全性时遇到了一些问题,特别是用户和管理员角色。我希望每个角色类型重定向到其各自的页面/用户和/管理员。我已经阅读了无数的教程,每一个似乎都有点不同于上一个,这一切都非常混乱。我想知道是否有人能定义我需要做什么,因为我不认为我离我目前所做的事情太远了。目前的问题是,它没有像我登录后试图检索Prinicipal.getName()时那样重定向,我不认为它是在创建会话,因为它总是空的。除了这个我还缺什么吗?非常感谢您的帮助 几乎整个应用程序都包括注册功能、userRepo和视图
@Autowired
UserRepo userRepo;
public UserDetailService(UserRepo userRepo){
this.userRepo=userRepo;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//Find a user by username
User user = this.userRepo.findByUsername(username);
//Check if it's null
if(user == null) throw new UsernameNotFoundException(username);
//if not then return user detail with arguments
else return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), getAuthorities(user));
}
@SuppressWarnings("serial")
public static Collection<GrantedAuthority> getAuthorities(User user) {
// make everyone ROLE_USER
Collection<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
GrantedAuthority grantedAuthority = new GrantedAuthority() {
@Override
public String getAuthority() {
if (user.getRole().equals("ROLE_USER")) return "ROLE_USER";
else return "ROLE_ADMIN";
}
};
grantedAuthorities.add(grantedAuthority);
grantedAuthority = new GrantedAuthority() {
@Override
public String getAuthority() {
return "ROLE_USER";
}
};
grantedAuthorities.add(grantedAuthority);
return grantedAuthorities;
}
@Autowired
private UserRepo userRepo;
//User register service
public void register(User user) {
//Encrypt password
user.setPassword(BCrypt.hashpw(user.getPassword(), BCrypt.gensalt()));
user.setRole("ROLE_USER");
this.userRepo.save(user);
}
//Used to add admin accounts on boot
public void adminOnBoot(User user) {
user.setPassword(BCrypt.hashpw(user.getPassword(), BCrypt.gensalt()));
this.userRepo.save(user);
}
//Return the list of users available
public List<User> getAllUsers() {
return this.userRepo.findAll();
}
//Check if user exists by a username
public Boolean existsByUsername(String username) {
return this.userRepo.existsByUsername(username);
}
//Check if user exists by an email
public Boolean existsByEmail(String emailAddress) {
return this.userRepo.existsByEmail(emailAddress);
}
//Login user by the login forms username and password
public User loginUserByForm(LoginForm loginForm) {
User user = this.userRepo.findByUsername(loginForm.getUsername());
if(user != null && BCrypt.checkpw(loginForm.getPassword(), user.getPassword()))
return user;
else return null;
}
@Autowired
private UserServices userService;
//LOGIN PROCESS - NO NEED FOR SEPERATE VIEW
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String verifyLogin(@Valid @ModelAttribute("loginForm") LoginForm loginForm, Model model, HttpServletRequest request) {
User user = userService.loginUserByForm(loginForm);
if(user == null) {
//Add a model attribute for an error
model.addAttribute("loginError", "notNull");
//Passing the no. of registered users
model.addAttribute("users", userService.getAllUsers());
model.addAttribute("userCount", userService.getAllUsers().size());
return "index";
}
//create the HttpSession
request.getSession().setAttribute("user", user);
//Passing the no. of registered users
model.addAttribute("users", userService.getAllUsers());
model.addAttribute("userCount", userService.getAllUsers().size());
model.addAttribute("username", user.getUsername());
//TO DO
return "admin";
}
@RequestMapping("/logout")
public String verifyLogout(HttpServletRequest request, HttpServletResponse response) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null){
new SecurityContextLogoutHandler().logout(request, response, auth);
}
return "redirect:/login?logout";
}
@Autowired
private UserRepo userRepo;
@Autowired
private CustomAuthenticationHandler authHandler;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsServiceBean());
}
@Override
public UserDetailsService userDetailsServiceBean() throws Exception {
return new UserDetailService(userRepo);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
//CSS FILES AND IMAGES
.antMatchers("/css/**", "/img/**", "/js/**").permitAll()
//PAGES FOR ALL PEOPLE
.antMatchers("/", "/login", "/register/**").permitAll()
//PAGES FOR ADMIN
.antMatchers("/admin/**").hasAuthority("ADMIN")
//PAGES FOR USERS
.antMatchers("/user/**").hasAuthority("USER")
.anyRequest().authenticated()
.and()
.formLogin()
.loginProcessingUrl("/login")
.loginPage("/")
.failureUrl("/?error")
.and()
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/");
;
}
@Autowired
UserRepo userRepo;
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws ServletException, IOException {
HttpSession session = request.getSession();
User user = userRepo.findByUsername(authentication.getName());
session.setAttribute("user", user);
response.setStatus(HttpServletResponse.SC_OK);
if (user.getRole().equals("ROLE_ADMIN")) {
response.sendRedirect("/admin/");
} else {
response.sendRedirect("/user/" + user.getUsername());
}
}
}
@配置
@启用Web安全性
公共类SpringSecurityConfigure扩展了WebSecurity配置适配器{
@Autowired
UserRepo userRepo;
public UserDetailService(UserRepo userRepo){
this.userRepo=userRepo;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//Find a user by username
User user = this.userRepo.findByUsername(username);
//Check if it's null
if(user == null) throw new UsernameNotFoundException(username);
//if not then return user detail with arguments
else return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), getAuthorities(user));
}
@SuppressWarnings("serial")
public static Collection<GrantedAuthority> getAuthorities(User user) {
// make everyone ROLE_USER
Collection<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
GrantedAuthority grantedAuthority = new GrantedAuthority() {
@Override
public String getAuthority() {
if (user.getRole().equals("ROLE_USER")) return "ROLE_USER";
else return "ROLE_ADMIN";
}
};
grantedAuthorities.add(grantedAuthority);
grantedAuthority = new GrantedAuthority() {
@Override
public String getAuthority() {
return "ROLE_USER";
}
};
grantedAuthorities.add(grantedAuthority);
return grantedAuthorities;
}
@Autowired
private UserRepo userRepo;
//User register service
public void register(User user) {
//Encrypt password
user.setPassword(BCrypt.hashpw(user.getPassword(), BCrypt.gensalt()));
user.setRole("ROLE_USER");
this.userRepo.save(user);
}
//Used to add admin accounts on boot
public void adminOnBoot(User user) {
user.setPassword(BCrypt.hashpw(user.getPassword(), BCrypt.gensalt()));
this.userRepo.save(user);
}
//Return the list of users available
public List<User> getAllUsers() {
return this.userRepo.findAll();
}
//Check if user exists by a username
public Boolean existsByUsername(String username) {
return this.userRepo.existsByUsername(username);
}
//Check if user exists by an email
public Boolean existsByEmail(String emailAddress) {
return this.userRepo.existsByEmail(emailAddress);
}
//Login user by the login forms username and password
public User loginUserByForm(LoginForm loginForm) {
User user = this.userRepo.findByUsername(loginForm.getUsername());
if(user != null && BCrypt.checkpw(loginForm.getPassword(), user.getPassword()))
return user;
else return null;
}
@Autowired
private UserServices userService;
//LOGIN PROCESS - NO NEED FOR SEPERATE VIEW
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String verifyLogin(@Valid @ModelAttribute("loginForm") LoginForm loginForm, Model model, HttpServletRequest request) {
User user = userService.loginUserByForm(loginForm);
if(user == null) {
//Add a model attribute for an error
model.addAttribute("loginError", "notNull");
//Passing the no. of registered users
model.addAttribute("users", userService.getAllUsers());
model.addAttribute("userCount", userService.getAllUsers().size());
return "index";
}
//create the HttpSession
request.getSession().setAttribute("user", user);
//Passing the no. of registered users
model.addAttribute("users", userService.getAllUsers());
model.addAttribute("userCount", userService.getAllUsers().size());
model.addAttribute("username", user.getUsername());
//TO DO
return "admin";
}
@RequestMapping("/logout")
public String verifyLogout(HttpServletRequest request, HttpServletResponse response) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null){
new SecurityContextLogoutHandler().logout(request, response, auth);
}
return "redirect:/login?logout";
}
@Autowired
private UserRepo userRepo;
@Autowired
private CustomAuthenticationHandler authHandler;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsServiceBean());
}
@Override
public UserDetailsService userDetailsServiceBean() throws Exception {
return new UserDetailService(userRepo);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
//CSS FILES AND IMAGES
.antMatchers("/css/**", "/img/**", "/js/**").permitAll()
//PAGES FOR ALL PEOPLE
.antMatchers("/", "/login", "/register/**").permitAll()
//PAGES FOR ADMIN
.antMatchers("/admin/**").hasAuthority("ADMIN")
//PAGES FOR USERS
.antMatchers("/user/**").hasAuthority("USER")
.anyRequest().authenticated()
.and()
.formLogin()
.loginProcessingUrl("/login")
.loginPage("/")
.failureUrl("/?error")
.and()
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/");
;
}
@Autowired
UserRepo userRepo;
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws ServletException, IOException {
HttpSession session = request.getSession();
User user = userRepo.findByUsername(authentication.getName());
session.setAttribute("user", user);
response.setStatus(HttpServletResponse.SC_OK);
if (user.getRole().equals("ROLE_ADMIN")) {
response.sendRedirect("/admin/");
} else {
response.sendRedirect("/user/" + user.getUsername());
}
}
}
公共类CustomAuthenticationHandler实现AuthenticationSuccessHandler{
@Autowired
UserRepo userRepo;
public UserDetailService(UserRepo userRepo){
this.userRepo=userRepo;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//Find a user by username
User user = this.userRepo.findByUsername(username);
//Check if it's null
if(user == null) throw new UsernameNotFoundException(username);
//if not then return user detail with arguments
else return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), getAuthorities(user));
}
@SuppressWarnings("serial")
public static Collection<GrantedAuthority> getAuthorities(User user) {
// make everyone ROLE_USER
Collection<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
GrantedAuthority grantedAuthority = new GrantedAuthority() {
@Override
public String getAuthority() {
if (user.getRole().equals("ROLE_USER")) return "ROLE_USER";
else return "ROLE_ADMIN";
}
};
grantedAuthorities.add(grantedAuthority);
grantedAuthority = new GrantedAuthority() {
@Override
public String getAuthority() {
return "ROLE_USER";
}
};
grantedAuthorities.add(grantedAuthority);
return grantedAuthorities;
}
@Autowired
private UserRepo userRepo;
//User register service
public void register(User user) {
//Encrypt password
user.setPassword(BCrypt.hashpw(user.getPassword(), BCrypt.gensalt()));
user.setRole("ROLE_USER");
this.userRepo.save(user);
}
//Used to add admin accounts on boot
public void adminOnBoot(User user) {
user.setPassword(BCrypt.hashpw(user.getPassword(), BCrypt.gensalt()));
this.userRepo.save(user);
}
//Return the list of users available
public List<User> getAllUsers() {
return this.userRepo.findAll();
}
//Check if user exists by a username
public Boolean existsByUsername(String username) {
return this.userRepo.existsByUsername(username);
}
//Check if user exists by an email
public Boolean existsByEmail(String emailAddress) {
return this.userRepo.existsByEmail(emailAddress);
}
//Login user by the login forms username and password
public User loginUserByForm(LoginForm loginForm) {
User user = this.userRepo.findByUsername(loginForm.getUsername());
if(user != null && BCrypt.checkpw(loginForm.getPassword(), user.getPassword()))
return user;
else return null;
}
@Autowired
private UserServices userService;
//LOGIN PROCESS - NO NEED FOR SEPERATE VIEW
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String verifyLogin(@Valid @ModelAttribute("loginForm") LoginForm loginForm, Model model, HttpServletRequest request) {
User user = userService.loginUserByForm(loginForm);
if(user == null) {
//Add a model attribute for an error
model.addAttribute("loginError", "notNull");
//Passing the no. of registered users
model.addAttribute("users", userService.getAllUsers());
model.addAttribute("userCount", userService.getAllUsers().size());
return "index";
}
//create the HttpSession
request.getSession().setAttribute("user", user);
//Passing the no. of registered users
model.addAttribute("users", userService.getAllUsers());
model.addAttribute("userCount", userService.getAllUsers().size());
model.addAttribute("username", user.getUsername());
//TO DO
return "admin";
}
@RequestMapping("/logout")
public String verifyLogout(HttpServletRequest request, HttpServletResponse response) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null){
new SecurityContextLogoutHandler().logout(request, response, auth);
}
return "redirect:/login?logout";
}
@Autowired
private UserRepo userRepo;
@Autowired
private CustomAuthenticationHandler authHandler;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsServiceBean());
}
@Override
public UserDetailsService userDetailsServiceBean() throws Exception {
return new UserDetailService(userRepo);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
//CSS FILES AND IMAGES
.antMatchers("/css/**", "/img/**", "/js/**").permitAll()
//PAGES FOR ALL PEOPLE
.antMatchers("/", "/login", "/register/**").permitAll()
//PAGES FOR ADMIN
.antMatchers("/admin/**").hasAuthority("ADMIN")
//PAGES FOR USERS
.antMatchers("/user/**").hasAuthority("USER")
.anyRequest().authenticated()
.and()
.formLogin()
.loginProcessingUrl("/login")
.loginPage("/")
.failureUrl("/?error")
.and()
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/");
;
}
@Autowired
UserRepo userRepo;
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws ServletException, IOException {
HttpSession session = request.getSession();
User user = userRepo.findByUsername(authentication.getName());
session.setAttribute("user", user);
response.setStatus(HttpServletResponse.SC_OK);
if (user.getRole().equals("ROLE_ADMIN")) {
response.sendRedirect("/admin/");
} else {
response.sendRedirect("/user/" + user.getUsername());
}
}
}问题在于您的角色定义: 在您的网站安全配置中您正在使用管理
.antMatchers("/admin/**").hasAuthority("ADMIN")
但是您正在寻找角色_ADMIN重定向到/ADMIN
user.getRole().equals("ROLE_ADMIN")
与用户相同,您正在查找用户,但您已经定义了角色\u用户
您好,几个小时后,我终于设法让它工作了。对于任何有类似自定义登录表单问题的人(不是j_spring_security_check…),我设置了一个新的CustomAuthenticationProvider.java
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
User user = userRepo.findByUsername(authentication.getName());
String name = authentication.getName();
String password = authentication.getCredentials().toString();
if(user != null) return new UsernamePasswordAuthenticationToken(name, password, getAuthorities(user));
return null;
}
我认为它添加到安全配置如下
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(cap);
}
简单的修复确实很简单,但会让人混淆太多不同的信息。
当做
Ben我已将其更改为以下
.access(“hasAuthority('USER')”)
并且仍然执行相同的操作,它现在正在到达.failureUrl。您可以发布日志问题吗?您是否尝试以管理员身份登录?嗨,伙计们---解决了什么问题?问题是我没有自己的身份验证方法的实现,所以它无法工作。只需要添加它,并在安全配置中将其配置为身份验证提供程序。我已经发布了我所更改的内容。感谢您的回复!