springboot11-01-security入门
Posted @yang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot11-01-security入门相关的知识,希望对你有一定的参考价值。
场景:
有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>
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"; } }
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 }
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 }
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 }
启动app类,访问:http:localhost:8080
登录用户名/密码: admin / admin
以上是关于springboot11-01-security入门的主要内容,如果未能解决你的问题,请参考以下文章