Spring security登録と権限キャラクター制御を実現します。


随筆のあらまし
1、springバージョン:4.3.22.RELEASE+spring securityバージョン:4.1.2.RELEASE(その他は説明しない)
2、展示されている内容は全部注釈で構成されています。
3、スプリングmvcはすでに配置されていますので、説明しません。
4、springmvc、spel、elに関わることができます。よく知らない人は先にこの内容を見に行ってもいいです。特にspringmvc 
まず、ログインには何が必要ですか?一番簡単な場合、ユーザー名、パスワードをデータベースと照合して、一致すれば個人ページにジャンプします。そうでないとログインページに戻り、ユーザー名のパスワードが間違っていることを示します。このプロセスにはまだ権限のある役割があるはずです。セッション全体を通して。この考え方があったら、私達はデータベースのユーザー名パスワードをspring securityに渡して、securityに関連してジャンプさせて、そしてsecurityに権限の役割とユーザ名をセッション全体に通してください。実際には、正しいユーザ名とパスワードと配置下のsecurityだけを提供する必要があります。  
目次
準備工作
ログインページ
個人ページ
spring securityの設定を開始します。
1.spring securityを起動する
2.設定権限
3.UserDetail Serviceを作成する 
まず、データベーステーブルを準備します。

CREATE TABLE `user` (
 `username` varchar(255) NOT NULL,
 `password` char(255) NOT NULL,
 `roles` enum('MEMBER','MEMBER,LEADER','SUPER_ADMIN') NOT NULL DEFAULT 'MEMBER',
 PRIMARY KEY (`username`),
 KEY `username` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
PS:ここで注意しているのはrolesの内容です。LEADERもメンバーです。そうすると、LEADERはメンバーの権限を持っています。もちろん、あなたもアプリの中で判断できます。この後に言います。
 ログインページ

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
 <title>  </title>
</head>
<body>
<div >
 
 <sf:form action="${pageContext.request.contextPath}/log" method="POST" commandName="user">  <!-- spring    ,              CSRF token   -->
  <h1 >  </h1>
  <c:if test="${error==true}"><p style="color: red">        </p></c:if>      <!--            -->
  <c:if test="${logout==true}"><p >     </p></c:if>                    <!--            -->
  <sf:input path="username" name="user.username" placeholder="    " /><br />
  <sf:password path="password" name="user.password" placeholder="    " /><br />
  <input id="remember-me" name="remember-me" type="checkbox"/>                <!--            -->
  <label for="remember-me">      </label>
  <input type="submit" class="sumbit" value="  " >
 </sf:form>
</div>
</body>
</html> 
個人ページ

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false"%>
<%@taglib prefix="security" uri="http://www.springframework.org/security/tags" %>
<%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
 <title>   ,<security:authentication property="principal.username" var="username"/>${username}</title>      <!--          ,  var       username  ,       EL   -->
</head>
<body>
<security:authorize access="isAuthenticated()"><h3>    !${username}</h3></security:authorize>  <!--           -->

<security:authorize access="hasRole('MEMBER')">              <!-- MENBER       security:authorize      -->
 <p>  MENBER</p>
</security:authorize>

<security:authorize access="hasRole('LEADER')">
 <p>  LEADER</p>
</security:authorize>


<sf:form id="logoutForm" action="${pageContext.request.contextPath}/logout" method="post">      <!--     ,     post,get        -->
 <a href="#" onclick="document.getElementById('logoutForm').submit();">  </a>
</sf:form>
</body>
</html>
spring securityの設定を開始します。
1.spring securityを起動する

@Order(2)
public class WebSecurityAppInit extends AbstractSecurityWebApplicationInitializer{
}
AbstractSecurity WebAppleication Initializerを継承して、spring securityは自動的に準備作業を行います。ここ@Order(2)は前の私のsprigmvcです。spring securityと一緒に起動エラーが発生しました。
2.設定権限

@Configuration
@EnableWebSecurity
@ComponentScan("com.chuanzhi.workspace.service.impl.*")
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{          

 @Autowired
 private UserDetailService userDetailService;  //  userDetailService          @ComponentScan

 @Override
 protected void configure(HttpSecurity http) throws Exception {
  http.authorizeRequests()
     .antMatchers("/me").hasAnyRole("MEMBER","SUPER_ADMIN")//         MENBER,SUPER_ADMIN       
     .anyRequest().authenticated()
     .and()
    .formLogin()
     .loginPage("/").permitAll()        //              ,         
     .loginProcessingUrl("/log")         //       url
     .failureForwardUrl("/?error=true")   //        ,        ,  error        
     .defaultSuccessUrl("/me")        //     url,        
     .and()
    .logout().logoutUrl("/logout").permitAll().logoutSuccessUrl("/?logout=true")    //   ,       url,security     url    ,           ,      url,logout      
     .and()
    .rememberMe()
     .tokenValiditySeconds(604800)     //     ,cookies      
     .rememberMeParameter("remember-me")   //                 ,        
     .rememberMeCookieName("workspace");   //cookies   ,            cookies  
 }

 @Override
 public void configure(WebSecurity web) throws Exception {
  super.configure(web);
 }

 @Override
 protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  auth.userDetailsService(userDetailService);  //     userDetailService
 }
}

3.UserDetail Serviceを作成する
spring securityは私達のユーザー情報を取得するServiceに提供します。主にsecurityに検証ユーザの情報を提供します。ここで私達は自分の需要をカスタマイズできます。これはusernameによってデータベースからそのユーザの情報を取得して、securityに引き継ぎます。

@Service(value = "userDetailService")
public class UserDetailService implements UserDetailsService {

 @Autowired
 private UserRepository repository;          

 public UserDetailService(UserRepository userRepository){
  this.repository = userRepository;              //    ,       
 }

 public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

  User user = repository.findUserByUsername(username);
  if (user==null)
   throw new UsernameNotFoundException("        !");          //    ,             

  List<GrantedAuthority> list = new ArrayList<GrantedAuthority>();      //GrantedAuthority security      ,

  getRoles(user,list);              //    ,  list  

  org.springframework.security.core.userdetails.User auth_user = new
    org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),list);      //         User security
  return auth_user;
 }

 /**
  *       
  * @param user
  * @param list
  */
 public void getRoles(User user,List<GrantedAuthority> list){
  for (String role:user.getRoles().split(",")) {
   list.add(new SimpleGrantedAuthority("ROLE_"+role));          //       ROLE_,security           ,     ,  ROLE_MENBER  MENBER  ,CAN_SEND  CAN_SEND  
  }
 }
}
私の機能の有効性を覚えたいなら、今度ログインページに入って直接に個人のトップページにジャンプしてこのコントローラのコードを見てもいいです。

/**
  *     
  * @param
  * @return
  */
 @RequestMapping(value = "/")
 public String login(Model model,User user
   ,@RequestParam(value = "error",required = false) boolean error
   ,@RequestParam(value = "logout",required = false) boolean logout,HttpServletRequest request){
  model.addAttribute(user);
  //             
  Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
  if(authentication!=null&&
    !authentication.getPrincipal().equals("anonymousUser")&&
    authentication.isAuthenticated())
   return "me";
  if(error==true)
   model.addAttribute("error",error);
  if(logout==true)
   model.addAttribute("logout",logout);
  return "login";
 } 
結果の展示:

以上が本文の全部です。皆さんの勉強に役に立つように、私たちを応援してください。