1. 程式人生 > >springboot11-01-security入門

springboot11-01-security入門

首頁 factory pri extend adding close 服務類 http 退出登錄

場景:

有3個頁面:首頁、登錄頁、登錄成功後的主頁面,如下圖:

技術分享

技術分享

技術分享

如果沒有登錄,點擊“去主頁”,會跳轉到登錄頁

如果已經登錄,點擊“去主頁”,跳轉到主頁,顯示“hello 用戶名”

下面用springboot + spring security簡單實現:

1.新建maven項目,添加pom支持:

技術分享
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <project xmlns="http://maven.apache.org/POM/4.0.0"
 3          xmlns:xsi
="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 5 <modelVersion>4.0.0</modelVersion> 6 7 <groupId>com.mlxs.springboot11.security01</groupId> 8 <artifactId>springboot11-security01</
artifactId> 9 <version>1.0-SNAPSHOT</version> 10 11 <!--父依賴包--> 12 <parent> 13 <groupId>org.springframework.boot</groupId> 14 <artifactId>spring-boot-starter-parent</artifactId> 15 <version>1.4.2.RELEASE</version
> 16 <relativePath/> 17 </parent> 18 19 <properties> 20 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 21 <java.version>1.8</java.version> 22 </properties> 23 24 <dependencies> 25 <dependency> 26 <groupId>org.springframework.boot</groupId> 27 <artifactId>spring-boot-starter</artifactId> 28 </dependency> 29 <!--測試--> 30 <dependency> 31 <groupId>org.springframework.boot</groupId> 32 <artifactId>spring-boot-starter-test</artifactId> 33 <scope>test</scope> 34 </dependency> 35 <!--mvc--> 36 <dependency> 37 <groupId>org.springframework.boot</groupId> 38 <artifactId>spring-boot-starter-web</artifactId> 39 </dependency> 40 <!-- security --> 41 <dependency> 42 <groupId>org.springframework.boot</groupId> 43 <artifactId>spring-boot-starter-security</artifactId> 44 </dependency> 45 <dependency> 46 <groupId>org.springframework.boot</groupId> 47 <artifactId>spring-boot-starter-thymeleaf</artifactId> 48 </dependency> 49 </dependencies> 50 </project>
View Code

2.boot啟動類

@SpringBootApplication
public class StartApp {

    public static void main(String[] args) {
        SpringApplication.run(StartApp.class, args);
    }
}

3.頁面控制器類:

技術分享
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * UserController類描述:
 *
 * @author yangzhenlong
 * @since 2017/5/23
 */
@Controller
public class UserController {

    @RequestMapping(value = "/")
    public String index(){
        return "/index";
    }

    @RequestMapping(value = "/login")
    public String login(){
        return "/login";
    }

    @RequestMapping(value = "/home")
    public String home(){
        return "/home";
    }
}
View Code

4.WebSecurityConfig配置類

技術分享
 1 package com.mlxs.security.config;
 2 
 3 
 4 import com.mlxs.util.MD5Util;
 5 import org.springframework.beans.factory.annotation.Autowired;
 6 import org.springframework.context.annotation.Bean;
 7 import org.springframework.context.annotation.Configuration;
 8 import org.springframework.security.authentication.AuthenticationManager;
 9 import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
10 import org.springframework.security.config.annotation.web.builders.HttpSecurity;
11 import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
12 import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
13 import org.springframework.security.crypto.password.PasswordEncoder;
14 
15 /**
16  * WebSecurityConfig類描述:
17  *
18  * @author yangzhenlong
19  * @since 2017/5/18
20  */
21 @Configuration
22 @EnableWebSecurity
23 //@EnableGlobalMethodSecurity(prePostEnabled = true)//允許進入頁面方法前檢驗
24 public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
25 
26     @Bean
27     @Override
28     protected AuthenticationManager authenticationManager() throws Exception {
29         return super.authenticationManager();
30     }
31 
32     @Override
33     protected void configure(HttpSecurity httpSecurity) throws Exception {
34 
35         httpSecurity.authorizeRequests()
36                 .antMatchers("/", "/login").permitAll() //無需驗證權限
37                 .anyRequest().authenticated() //其他地址的訪問均需驗證權限
38                 .and().formLogin().loginPage("/login").defaultSuccessUrl("/home").permitAll()//指定登錄頁是"/login" //登錄成功後默認跳轉到"/home"
39                 .and().logout().logoutSuccessUrl("/login").permitAll(); //退出登錄後的默認url是"/login"
40     }
41 
42     /**
43      * 全局配置
44      * @param builder
45      * @throws Exception
46      */
47     @Autowired
48     public void configure(AuthenticationManagerBuilder builder) throws Exception {
49         builder
50                 .userDetailsService(this.myUDService())
51                 .passwordEncoder(this.passwordEncoder());
52         //或者用下面的方式,直接配置固定的用戶和對應的角色
53         /*builder.inMemoryAuthentication().withUser("test").password("1234").roles("USER");
54         builder.inMemoryAuthentication().withUser("admin").password("admin").roles("ADMIN");
55         builder.inMemoryAuthentication().withUser("dba").password("root").roles("ADMIN","DBA");*/
56     }
57 
58     /**
59      * 設置用戶密碼的加密方式:MD5加密
60      * @return
61      */
62     @Bean
63     public PasswordEncoder passwordEncoder(){
64         PasswordEncoder pe = new PasswordEncoder() {//自定義密碼加密方式
65             //加密
66             @Override
67             public String encode(CharSequence charSequence) {
68                 return MD5Util.encode((String)charSequence);
69             }
70 
71             //校驗密碼
72             @Override
73             public boolean matches(CharSequence charSequence, String s) {
74                 return MD5Util.encode((String)charSequence).equals(s);
75             }
76         };
77         return pe;
78     }
79 
80     /**
81      * 自定義用戶服務,獲取用戶信息
82      * @return
83      */
84     @Bean
85     public MyUDService myUDService(){
86         return new MyUDService();
87     }
88 }
View Code

5.MD5工具類:

技術分享
 1 public class MD5Util {
 2 
 3     private static final String SALT = "test";//鹽值
 4 
 5     public static String encode(String password) {
 6         password = password + SALT;
 7         MessageDigest md5 = null;
 8         try {
 9             md5 = MessageDigest.getInstance("MD5");
10         } catch (Exception e) {
11             throw new RuntimeException(e);
12         }
13         char[] charArray = password.toCharArray();
14         byte[] byteArray = new byte[charArray.length];
15 
16         for (int i = 0; i < charArray.length; i++)
17             byteArray[i] = (byte) charArray[i];
18         byte[] md5Bytes = md5.digest(byteArray);
19         StringBuffer hexValue = new StringBuffer();
20         for (int i = 0; i < md5Bytes.length; i++) {
21             int val = ((int) md5Bytes[i]) & 0xff;
22             if (val < 16) {
23                 hexValue.append("0");
24             }
25 
26             hexValue.append(Integer.toHexString(val));
27         }
28         return hexValue.toString();
29     }
30 
31     /*public static void main(String[] args) {
32         System.out.println(MD5Util.encode("admin"));
33 
34         System.out.println("是否相等:" + MD5Util.encode("admin").equals("66d4aaa5ea177ac32c69946de3731ec0"));
35     }*/
36 }
View Code

6.用戶信息服務類

技術分享
 1 package com.mlxs.security.config;
 2 
 3 
 4 import org.springframework.security.core.authority.SimpleGrantedAuthority;
 5 import org.springframework.security.core.userdetails.User;
 6 import org.springframework.security.core.userdetails.UserDetails;
 7 import org.springframework.security.core.userdetails.UserDetailsService;
 8 import org.springframework.security.core.userdetails.UsernameNotFoundException;
 9 
10 import java.util.ArrayList;
11 import java.util.List;
12 
13 /**
14  * MyUDService類描述: 用戶服務類,用來從讀取用戶信息
15  *
16  * @author yangzhenlong
17  * @since 2017/5/22
18  */
19 public class MyUDService implements UserDetailsService {
20     @Override
21     public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
22         if(s.equals("admin")) {
23             List<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>();
24             authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
25 
26             User user = new User("admin", "66d4aaa5ea177ac32c69946de3731ec0", authorities);//用戶名和通過MD5加密後的密碼
27             return user;
28         }else{
29             throw new UsernameNotFoundException("UserName " + s + " not found");
30         }
31     }
32 
33 
34 }
View Code

啟動app類,訪問:http:localhost:8080

技術分享

登錄用戶名/密碼: admin / admin

springboot11-01-security入門