-1

我将开发一个使用spring启动和安全性的登录页面,用户和角色可以由admin创建,因此系统可以有多个角色和用户...也可以分配admin角色给用户并删除它们。 我已经使用了很好的示例来说明如何实现它,但在阅读了如此多的文档和教程后,仍然存在以下问题,并且不知道实现弹簧安全性和引导的最佳做法是什么。尝试在调试模式中找出一步一步地发生在场景后面的事情。Spring Boot和安全动态身份验证和授权

我的假设是针对每个http请求应用程序引用WebSecurityConfig类来检查访问,但令人惊讶的是,它不是那样的,而且其他人如下所示。似乎应用程序一开始就会配置类,并且每个东西都会填充。 bootstrap在后台做了很多动作,它让我感到困惑,无法理解类之间的关系。

configureGlobal - > configure - >无论你写为URL进入/登录) - >控制器(登录方法) - >用user/pass提交表单 - > loadUserByUsername - > controller (欢迎使用方法) - > welcome.jsp

1--什么是configureGlobal和configure在应用程序加载时执行的操作?

2-什么是AuthenticationManagerBuilder的确切作用?

3-spring spring security知道如何发送用户/将表单子传递给loadUserByUsername方法后?

4-loadUserByUsername返回用户对象到哪里?因为当方法到达最后时,它将重定向到控制器欢迎方法,并在用户名和密码正确时向您发送欢迎方法。

4 - 如何使用grantedAuthorities根据他的角色将用户重定向到不同的页面?

<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %> 
 
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 
 
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> 
 

 
<c:set var="contextPath" value="${pageContext.request.contextPath}"/> 
 

 
<!DOCTYPE html> 
 
<html lang="en"> 
 
<head> 
 
    <meta charset="utf-8"> 
 
    <meta http-equiv="X-UA-Compatible" content="IE=edge"> 
 
    <meta name="viewport" content="width=device-width, initial-scale=1"> 
 
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> 
 
    <meta name="description" content=""> 
 
    <meta name="author" content=""> 
 

 
    <title>Log in with your account</title> 
 

 
    <link href="${contextPath}/resources/css/bootstrap.min.css" rel="stylesheet"> 
 
    <link href="${contextPath}/resources/css/common.css" rel="stylesheet"> 
 

 
    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> 
 
    <!--[if lt IE 9]> 
 
    <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> 
 
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> 
 
    <![endif]--> 
 
</head> 
 

 
<body> 
 

 
<div class="container"> 
 

 
    <form method="POST" action="${contextPath}/login" class="form-signin"> 
 
     <h2 class="form-heading">Log in</h2> 
 
     <div class="form-group ${error != null ? 'has-error' : ''}"> 
 
      <span>${message}</span> 
 
      <input name="username" type="text" class="form-control" placeholder="Username" 
 
        autofocus="true"/> 
 
      <input name="password" type="password" class="form-control" placeholder="Password"/> 
 
      <span>${error}</span> 
 
      <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/> 
 

 
      <button class="btn btn-lg btn-primary btn-block" type="submit">Log In</button> 
 
      <h4 class="text-center"><a href="${contextPath}/registration">Create an account</a></h4> 
 
     </div> 
 
    </form> 
 

 
</div> 
 
<!-- /container --> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> 
 
<script src="${contextPath}/resources/js/bootstrap.min.js"></script> 
 
</body> 
 
</html>

WebSecurityConfig类

@Configuration 
@EnableWebSecurity 
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 

@Autowired 
private UserDetailsService userDetailsService; 

@Bean 
public BCryptPasswordEncoder bCryptPasswordEncoder() { 
    return new BCryptPasswordEncoder(); 
} 

@Override 
protected void configure(HttpSecurity http) throws Exception { 
    http 
      .authorizeRequests() 
       .antMatchers("/resources/**", "/registration").permitAll() 
       .anyRequest().authenticated() 
       .and() 
      .formLogin() 
       .loginPage("/login").permitAll() 
       .and() 
      .logout().permitAll(); 

} 

@Autowired 
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { 
    auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder()); 
} 
} 

UserDetailsS​​erviceImpl类

@Service 
public class UserDetailsServiceImpl implements UserDetailsService{ 

@Autowired 
private UserRepository userRepository; 

@Override 
@Transactional(readOnly = true) 
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { 

    User user = userRepository.findByUsername(username); 

    Set<GrantedAuthority> grantedAuthorities = new HashSet<>(); 

    for (Role role : user.getRoles()){ 
     grantedAuthorities.add(new SimpleGrantedAuthority(role.getName())); 
    } 

    return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), grantedAuthorities); 

} 
} 

UserController类

@Controller 
public class UserController { 
@Autowired 
private UserService userService; 

@Autowired 
private SecurityService securityService; 

@Autowired 
private UserValidator userValidator; 

@RequestMapping(value = "/registration", method = RequestMethod.GET) 
public String registration(Model model) { 
    model.addAttribute("userForm", new User()); 

    return "registration"; 
} 

@RequestMapping(value = "/registration", method = RequestMethod.POST) 
public String registration(@ModelAttribute("userForm") User userForm, BindingResult bindingResult, Model model) { 

    userValidator.validate(userForm, bindingResult); 

    if (bindingResult.hasErrors()) { 
     return "registration"; 
    } 

    userService.save(userForm); 

    securityService.autologin(userForm.getUsername(), userForm.getPasswordConfirm()); 

    return "redirect:/welcome"; 
} 

@RequestMapping(value = "/login", method = RequestMethod.GET) 
public String login(Model model, String error, String logout) { 
    if (error != null) 
     model.addAttribute("error", "Your username and password is invalid."); 

    if (logout != null) 
     model.addAttribute("message", "You have been logged out successfully."); 

    return "login"; 
} 

@RequestMapping(value = {"/", "/welcome"}, method = RequestMethod.GET) 
public String welcome(Model model) { 
    return "welcome"; 
} 


} 
+0

彼得,你的问题太广泛了。在你遇到的问题中更具体一些,展示你的尝试并一次提出一个问题。 – jfneis

回答

0

我想和大家分享的一些问题,这是很清楚,我现在的答案。

  1. 当您启动项目

    ,首先它去WebSecurityConfig类并查找configureGlobal方法建立认证过程,然后查找配置方法来设置安全性。

  2. AuthenticationManagerBuilder与许多方法,例如的UserDetailsS​​ervice这是用来验证基于用户信息的一类,所以当你登录它会发送credentails到已经实施UserDetailsS​​ervice的接口的类。

  3. POST到/login URL将尝试对用户进行身份验证,因此configureGlobal将执行必要操作。

  4. 它已从调用configureGlobal方法并返回支持那里,仍然一切都在根路径,因此将在控制器类中找到适当的方法。

  5. AuthenticationSuccessHandler可以在这方面提供帮助。