-1

我将使用 Spring Boot 和安全性开发一个登录页面,管理员可以创建用户和角色,因此系统可以有许多角色和用户......管理员也可以将角色分配给用户并删除它们。我已经使用了很好的示例来说明如何实现它,但是在阅读了这么多文档和教程之后仍然有以下问题,并且不知道实现 spring 安全性和一起启动的最佳实践是什么。尝试进入调试模式以找出什么正在一步步发生在幕后。

我的假设是每个 http 请求应用程序都引用 WebSecurityConfig 类来检查访问,但令人惊讶的是它不是那样的,同伴如下所示。似乎应用程序一开始就进入 config 类,每件事都填充。bootstrap 做了这么多后台操作,这让我感到困惑,无法理解类之间的关系。

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

1-应用程序加载时 configureGlobal 和 configure 究竟做了什么?

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

3-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);

}
}

用户控制器类

@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";
}


}
4

1 回答 1

1

我想分享一些我现在很清楚的问题的答案。

  1. 当你开始你的项目时,首先它进入WebSecurityConfig类并寻找configureGlobal方法来构建身份验证过程,然后寻找configure方法来设置安全性。

  2. AuthenticationManagerBuilder是一个具有许多方法的类,例如userDetailsS​​ervice,它用于根据用户详细信息进行身份验证,因此当您登录时,它会将凭据发送到已实现UserDetailsS ​​ervice接口的类。

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

  4. 它已从configureGlobal方法调用并返回到那里,并且仍然所有内容都在根路径中,因此将在控制器类中找到正确的方法。

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

于 2017-09-21T12:33:10.917 回答