-1

私は春の起動とセキュリティを使用してユーザーとロールを管理者が作成できるように、システムに多数のロールとユーザーを割り当てることができるログインページを開発するつもりです。ユーザーにロールを割り当て、それらも削除します。 私はそれを実装する方法の良いサンプルを使用しましたが、docやチュートリアルを読んだり、以下の質問が残っていたり、春のセキュリティとブートを実装するベストプラクティスがわからない場合は、シーンの後ろで何が起こっているのかを段階的に示します。スプリングブートとセキュリティダイナミック認証と認証

私の前提は、すべてのhttp要求アプリケーションがWebSecurityConfigクラスを参照してアクセスをチェックすることですが、驚くことではありませんでしたし、仲間は以下のようでした.seemsアプリケーションは最初にconfigクラスに移動し、ブートストラップはバックグラウンドで非常に多くのアクションを行い、混乱させ、クラス間の関係を理解できませんでした。 /ログイン - >コントローラ(ログイン方法) - >ユーザー/パス - > loadUserByUsername - >コントローラを使用してフォームを送信します。 (ウェルカムメソッド) - > welcome.jsp

1 - アプリケーションがをロードするときに、正確にconfigureGlobalとconfigureが何をするのですか?

2 - AuthenticationManagerBuilderの役割は何ですか?

3-springセキュリティが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

Peter、あなたの質問は広すぎます。あなたが持っている問題をより具体的にして、あなたが試したことを示し、一度に1つの質問をしてください。 – jfneis

答えて

0

私は今、私にははっきりしているいくつかの質問の答えを共有したいと思います。

  1. あなたは、あなたのプロジェクトを開始することがWebSecurityConfigクラスに行くすべての最初の、認証プロセスを構築するためのconfigureGlobal方法を探した後、のconfigureのセキュリティを設定する方法を探します。

  2. AuthenticationManagerBuilderあなたはログインしたときにそれがUserDetailsS​​erviceインタフェースを実装したクラスにcredentailsを送信するユーザーの詳細情報に基づいて認証するために使用されるuserDetailsS​​erviceのような多くのメソッドを持つクラスです。

  3. /loginのURLは、ユーザーの認証を試み、configureGlobalは必要な処理を行います。

  4. configureGlobalメソッドが呼び出され、そこに戻ってきて、すべてがルートパスにあるので、コントローラクラスで適切なメソッドが見つけられます。

  5. AuthenticationSuccessHandlerがこの点で役立ちます。