├── .gitignore ├── README.md ├── distributed-security ├── distributed-security-discovery │ ├── pom.xml │ └── src │ │ └── main │ │ ├── java │ │ └── com │ │ │ └── pbteach │ │ │ └── security │ │ │ └── distributed │ │ │ └── discovery │ │ │ └── DiscoveryServer.java │ │ └── resources │ │ └── application.yml ├── distributed-security-gateway │ ├── pom.xml │ └── src │ │ └── main │ │ ├── java │ │ └── com │ │ │ └── pbteach │ │ │ └── security │ │ │ └── distributed │ │ │ └── gateway │ │ │ ├── GatewayServer.java │ │ │ ├── common │ │ │ └── EncryptUtil.java │ │ │ ├── config │ │ │ ├── ResouceServerConfig.java │ │ │ ├── TokenConfig.java │ │ │ ├── WebSecurityConfig.java │ │ │ └── ZuulConfig.java │ │ │ └── filter │ │ │ └── AuthFilter.java │ │ └── resources │ │ └── application.properties ├── distributed-security-order │ ├── pom.xml │ └── src │ │ └── main │ │ ├── java │ │ └── com │ │ │ └── pbteach │ │ │ └── security │ │ │ └── distributed │ │ │ └── order │ │ │ ├── OrderServer.java │ │ │ ├── common │ │ │ └── EncryptUtil.java │ │ │ ├── config │ │ │ ├── ResouceServerConfig.java │ │ │ ├── TokenConfig.java │ │ │ └── WebSecurityConfig.java │ │ │ ├── controller │ │ │ └── OrderController.java │ │ │ ├── filter │ │ │ └── TokenAuthenticationFilter.java │ │ │ └── model │ │ │ └── UserDTO.java │ │ └── resources │ │ └── application.properties ├── distributed-security-uaa │ ├── pom.xml │ └── src │ │ └── main │ │ ├── java │ │ └── com │ │ │ └── pbteach │ │ │ └── security │ │ │ └── distributed │ │ │ └── uaa │ │ │ ├── UAAServer.java │ │ │ ├── config │ │ │ ├── AuthorizationServer.java │ │ │ ├── TokenConfig.java │ │ │ └── WebSecurityConfig.java │ │ │ ├── dao │ │ │ └── UserDao.java │ │ │ ├── model │ │ │ ├── PermissionDto.java │ │ │ └── UserDto.java │ │ │ └── service │ │ │ └── SpringDataUserDetailsService.java │ │ └── resources │ │ └── application.properties └── pom.xml ├── security-spring-boot ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── pbteach │ │ │ └── security │ │ │ └── springboot │ │ │ ├── SecuritySpringBootApp.java │ │ │ ├── config │ │ │ ├── WebConfig.java │ │ │ └── WebSecurityConfig.java │ │ │ ├── controller │ │ │ └── LoginController.java │ │ │ ├── dao │ │ │ └── UserDao.java │ │ │ ├── model │ │ │ ├── PermissionDto.java │ │ │ └── UserDto.java │ │ │ └── service │ │ │ └── SpringDataUserDetailsService.java │ ├── resources │ │ └── application.properties │ └── webapp │ │ └── WEB-INF │ │ └── view │ │ └── login.jsp │ └── test │ └── java │ └── com │ └── pbteach │ └── security │ └── springboot │ └── TestBCrypt.java ├── security-spring-security ├── pom.xml └── src │ └── main │ └── java │ └── com │ └── pbteach │ └── security │ └── springmvc │ ├── config │ ├── ApplicationConfig.java │ ├── WebConfig.java │ └── WebSecurityConfig.java │ ├── controller │ └── LoginController.java │ └── init │ ├── SpringApplicationInitializer.java │ └── SpringSecurityApplicationInitializer.java └── security-springmvc ├── pom.xml └── src └── main ├── java └── com │ └── pbteach │ └── security │ └── springmvc │ ├── config │ ├── ApplicationConfig.java │ └── WebConfig.java │ ├── controller │ └── LoginController.java │ ├── init │ └── SpringApplicationInitializer.java │ ├── interceptor │ └── SimpleAuthenticationInterceptor.java │ ├── model │ ├── AuthenticationRequest.java │ └── UserDto.java │ └── service │ ├── AuthenticationService.java │ └── AuthenticationServiceImpl.java └── webapp └── WEB-INF └── view └── login.jsp /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | target/ 3 | *.iml 4 | pom.xml.tag 5 | pom.xml.releaseBackup 6 | pom.xml.versionsBackup 7 | pom.xml.next 8 | release.properties 9 | dependency-reduced-pom.xml 10 | buildNumber.properties 11 | .mvn/timing.properties 12 | 13 | # Avoid ignoring Maven wrapper jar file (.jar files are usually ignored) 14 | !/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SpringSecurity 2 | ## 讲义清单: 3 | 4 | http://www.pbteach.com/post/java_distribut/springsecurity-01/ 5 | 6 | http://www.pbteach.com/post/java_distribut/springsecurity-02/ 7 | 8 | http://www.pbteach.com/post/java_distribut/springsecurity-03/ 9 | 10 | http://www.pbteach.com/post/java_distribut/springsecurity-04/ 11 | 12 | http://www.pbteach.com/post/java_distribut/springsecurity-05/ 13 | 14 | http://www.pbteach.com/post/java_distribut/springsecurity-06/ 15 | 16 | http://www.pbteach.com/post/java_distribut/springsecurity-07/ 17 | 18 | http://www.pbteach.com/post/java_distribut/springsecurity-08/ 19 | 20 | http://www.pbteach.com/post/java_distribut/springsecurity-09/ 21 | 22 | http://www.pbteach.com/post/java_distribut/springsecurity-10/ 23 | 24 | http://www.pbteach.com/post/java_distribut/springsecurity-11/ 25 | 26 | http://www.pbteach.com/post/java_distribut/springsecurity-12/ 27 | 28 | 29 | 30 | ## 视频下载: 31 | 32 | http://www.pbteach.com/post/java_distribut/subject_springsecurity/ 33 | 34 | 35 | 36 | ## 代码下载: 37 | 38 | https://github.com/pbteach/SpringSecurity 39 | 40 | -------------------------------------------------------------------------------- /distributed-security/distributed-security-discovery/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | distributed-security 7 | com.pbteach.security 8 | 1.0-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | distributed-security-discovery 13 | 14 | 15 | org.springframework.cloud 16 | spring-cloud-starter-netflix-eureka-server 17 | 18 | 19 | 20 | org.springframework.boot 21 | spring-boot-starter-actuator 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /distributed-security/distributed-security-discovery/src/main/java/com/pbteach/security/distributed/discovery/DiscoveryServer.java: -------------------------------------------------------------------------------- 1 | package com.pbteach.security.distributed.discovery; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; 6 | 7 | /** 8 | * @author Administrator 9 | * @version 1.0 10 | **/ 11 | @SpringBootApplication 12 | @EnableEurekaServer 13 | public class DiscoveryServer { 14 | public static void main(String[] args) { 15 | SpringApplication.run(DiscoveryServer.class,args); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /distributed-security/distributed-security-discovery/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | application: 3 | name: distributed-discovery 4 | 5 | server: 6 | port: 53000 #启动端口 7 | 8 | eureka: 9 | server: 10 | enable-self-preservation: false #关闭服务器自我保护,客户端心跳检测15分钟内错误达到80%服务会保护,导致别人还认为是好用的服务 11 | eviction-interval-timer-in-ms: 10000 #清理间隔(单位毫秒,默认是60*1000)5秒将客户端剔除的服务在服务注册列表中剔除# 12 | shouldUseReadOnlyResponseCache: true #eureka是CAP理论种基于AP策略,为了保证强一致性关闭此切换CP 默认不关闭 false关闭 13 | client: 14 | register-with-eureka: false #false:不作为一个客户端注册到注册中心 15 | fetch-registry: false #为true时,可以启动,但报异常:Cannot execute request on any known server 16 | instance-info-replication-interval-seconds: 10 17 | serviceUrl: 18 | defaultZone: http://localhost:${server.port}/eureka/ 19 | instance: 20 | hostname: ${spring.cloud.client.ip-address} 21 | prefer-ip-address: true 22 | instance-id: ${spring.application.name}:${spring.cloud.client.ip-address}:${spring.application.instance_id:${server.port}} 23 | -------------------------------------------------------------------------------- /distributed-security/distributed-security-gateway/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | distributed-security 7 | com.pbteach.security 8 | 1.0-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | distributed-security-gateway 13 | 14 | 15 | 16 | org.springframework.cloud 17 | spring-cloud-starter-netflix-eureka-client 18 | 19 | 20 | 21 | org.springframework.cloud 22 | spring-cloud-starter-netflix-hystrix 23 | 24 | 25 | 26 | org.springframework.cloud 27 | spring-cloud-starter-netflix-ribbon 28 | 29 | 30 | 31 | org.springframework.cloud 32 | spring-cloud-starter-openfeign 33 | 34 | 35 | 36 | com.netflix.hystrix 37 | hystrix-javanica 38 | 39 | 40 | 41 | org.springframework.retry 42 | spring-retry 43 | 44 | 45 | 46 | org.springframework.boot 47 | spring-boot-starter-actuator 48 | 49 | 50 | 51 | org.springframework.boot 52 | spring-boot-starter-web 53 | 54 | 55 | 56 | org.springframework.cloud 57 | spring-cloud-starter-netflix-zuul 58 | 59 | 60 | 61 | org.springframework.cloud 62 | spring-cloud-starter-security 63 | 64 | 65 | 66 | org.springframework.cloud 67 | spring-cloud-starter-oauth2 68 | 69 | 70 | 71 | org.springframework.security 72 | spring-security-jwt 73 | 74 | 75 | 76 | javax.interceptor 77 | javax.interceptor-api 78 | 79 | 80 | 81 | com.alibaba 82 | fastjson 83 | 84 | 85 | org.projectlombok 86 | lombok 87 | 88 | 89 | 90 | 91 | -------------------------------------------------------------------------------- /distributed-security/distributed-security-gateway/src/main/java/com/pbteach/security/distributed/gateway/GatewayServer.java: -------------------------------------------------------------------------------- 1 | package com.pbteach.security.distributed.gateway; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.cloud.client.discovery.EnableDiscoveryClient; 6 | import org.springframework.cloud.netflix.zuul.EnableZuulProxy; 7 | 8 | /** 9 | * @author Administrator 10 | * @version 1.0 11 | **/ 12 | @SpringBootApplication 13 | @EnableZuulProxy 14 | @EnableDiscoveryClient 15 | public class GatewayServer { 16 | 17 | public static void main(String[] args) { 18 | SpringApplication.run(GatewayServer.class, args); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /distributed-security/distributed-security-gateway/src/main/java/com/pbteach/security/distributed/gateway/common/EncryptUtil.java: -------------------------------------------------------------------------------- 1 | package com.pbteach.security.distributed.gateway.common; 2 | 3 | 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | 7 | import java.io.UnsupportedEncodingException; 8 | import java.net.URLDecoder; 9 | import java.net.URLEncoder; 10 | import java.util.Base64; 11 | 12 | public class EncryptUtil { 13 | private static final Logger logger = LoggerFactory.getLogger(EncryptUtil.class); 14 | 15 | public static String encodeBase64(byte[] bytes){ 16 | String encoded = Base64.getEncoder().encodeToString(bytes); 17 | return encoded; 18 | } 19 | 20 | public static byte[] decodeBase64(String str){ 21 | byte[] bytes = null; 22 | bytes = Base64.getDecoder().decode(str); 23 | return bytes; 24 | } 25 | 26 | public static String encodeUTF8StringBase64(String str){ 27 | String encoded = null; 28 | try { 29 | encoded = Base64.getEncoder().encodeToString(str.getBytes("utf-8")); 30 | } catch (UnsupportedEncodingException e) { 31 | logger.warn("不支持的编码格式",e); 32 | } 33 | return encoded; 34 | 35 | } 36 | 37 | public static String decodeUTF8StringBase64(String str){ 38 | String decoded = null; 39 | byte[] bytes = Base64.getDecoder().decode(str); 40 | try { 41 | decoded = new String(bytes,"utf-8"); 42 | }catch(UnsupportedEncodingException e){ 43 | logger.warn("不支持的编码格式",e); 44 | } 45 | return decoded; 46 | } 47 | 48 | public static String encodeURL(String url) { 49 | String encoded = null; 50 | try { 51 | encoded = URLEncoder.encode(url, "utf-8"); 52 | } catch (UnsupportedEncodingException e) { 53 | logger.warn("URLEncode失败", e); 54 | } 55 | return encoded; 56 | } 57 | 58 | 59 | public static String decodeURL(String url) { 60 | String decoded = null; 61 | try { 62 | decoded = URLDecoder.decode(url, "utf-8"); 63 | } catch (UnsupportedEncodingException e) { 64 | logger.warn("URLDecode失败", e); 65 | } 66 | return decoded; 67 | } 68 | 69 | public static void main(String [] args){ 70 | String str = "abcd{'a':'b'}"; 71 | String encoded = EncryptUtil.encodeUTF8StringBase64(str); 72 | String decoded = EncryptUtil.decodeUTF8StringBase64(encoded); 73 | System.out.println(str); 74 | System.out.println(encoded); 75 | System.out.println(decoded); 76 | 77 | String url = "== wo"; 78 | String urlEncoded = EncryptUtil.encodeURL(url); 79 | String urlDecoded = EncryptUtil.decodeURL(urlEncoded); 80 | 81 | System.out.println(url); 82 | System.out.println(urlEncoded); 83 | System.out.println(urlDecoded); 84 | } 85 | 86 | 87 | } 88 | -------------------------------------------------------------------------------- /distributed-security/distributed-security-gateway/src/main/java/com/pbteach/security/distributed/gateway/config/ResouceServerConfig.java: -------------------------------------------------------------------------------- 1 | package com.pbteach.security.distributed.gateway.config; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 6 | import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; 7 | import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; 8 | import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; 9 | import org.springframework.security.oauth2.provider.token.TokenStore; 10 | 11 | /** 12 | * @author Administrator 13 | * @version 1.0 14 | **/ 15 | @Configuration 16 | public class ResouceServerConfig { 17 | 18 | public static final String RESOURCE_ID = "res1"; 19 | 20 | 21 | //uaa资源服务配置 22 | @Configuration 23 | @EnableResourceServer 24 | public class UAAServerConfig extends ResourceServerConfigurerAdapter { 25 | @Autowired 26 | private TokenStore tokenStore; 27 | 28 | @Override 29 | public void configure(ResourceServerSecurityConfigurer resources){ 30 | resources.tokenStore(tokenStore).resourceId(RESOURCE_ID) 31 | .stateless(true); 32 | } 33 | 34 | @Override 35 | public void configure(HttpSecurity http) throws Exception { 36 | http.authorizeRequests() 37 | .antMatchers("/uaa/**").permitAll(); 38 | } 39 | } 40 | 41 | 42 | //order资源 43 | //uaa资源服务配置 44 | @Configuration 45 | @EnableResourceServer 46 | public class OrderServerConfig extends ResourceServerConfigurerAdapter { 47 | @Autowired 48 | private TokenStore tokenStore; 49 | 50 | @Override 51 | public void configure(ResourceServerSecurityConfigurer resources){ 52 | resources.tokenStore(tokenStore).resourceId(RESOURCE_ID) 53 | .stateless(true); 54 | } 55 | 56 | @Override 57 | public void configure(HttpSecurity http) throws Exception { 58 | http 59 | .authorizeRequests() 60 | .antMatchers("/order/**").access("#oauth2.hasScope('ROLE_API')"); 61 | } 62 | } 63 | 64 | 65 | //配置其它的资源服务.. 66 | 67 | 68 | } 69 | -------------------------------------------------------------------------------- /distributed-security/distributed-security-gateway/src/main/java/com/pbteach/security/distributed/gateway/config/TokenConfig.java: -------------------------------------------------------------------------------- 1 | package com.pbteach.security.distributed.gateway.config; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.security.oauth2.provider.token.TokenStore; 6 | import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; 7 | import org.springframework.security.oauth2.provider.token.store.JwtTokenStore; 8 | 9 | /** 10 | * @author Administrator 11 | * @version 1.0 12 | **/ 13 | @Configuration 14 | public class TokenConfig { 15 | 16 | private String SIGNING_KEY = "uaa123"; 17 | 18 | @Bean 19 | public TokenStore tokenStore() { 20 | //JWT令牌存储方案 21 | return new JwtTokenStore(accessTokenConverter()); 22 | } 23 | 24 | @Bean 25 | public JwtAccessTokenConverter accessTokenConverter() { 26 | JwtAccessTokenConverter converter = new JwtAccessTokenConverter(); 27 | converter.setSigningKey(SIGNING_KEY); //对称秘钥,资源服务器使用该秘钥来验证 28 | return converter; 29 | } 30 | 31 | /* @Bean 32 | public TokenStore tokenStore() { 33 | //使用内存存储令牌(普通令牌) 34 | return new InMemoryTokenStore(); 35 | }*/ 36 | } 37 | -------------------------------------------------------------------------------- /distributed-security/distributed-security-gateway/src/main/java/com/pbteach/security/distributed/gateway/config/WebSecurityConfig.java: -------------------------------------------------------------------------------- 1 | package com.pbteach.security.distributed.gateway.config; 2 | 3 | import org.springframework.context.annotation.Configuration; 4 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 5 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 6 | 7 | /** 8 | * @author Administrator 9 | * @version 1.0 10 | **/ 11 | @Configuration 12 | public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 13 | 14 | @Override 15 | protected void configure(HttpSecurity http) throws Exception { 16 | 17 | http 18 | .authorizeRequests() 19 | .antMatchers("/**").permitAll() 20 | .and().csrf().disable(); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /distributed-security/distributed-security-gateway/src/main/java/com/pbteach/security/distributed/gateway/config/ZuulConfig.java: -------------------------------------------------------------------------------- 1 | package com.pbteach.security.distributed.gateway.config; 2 | 3 | import com.pbteach.security.distributed.gateway.filter.AuthFilter; 4 | import org.springframework.boot.web.servlet.FilterRegistrationBean; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.context.annotation.Configuration; 7 | import org.springframework.core.Ordered; 8 | import org.springframework.web.cors.CorsConfiguration; 9 | import org.springframework.web.cors.UrlBasedCorsConfigurationSource; 10 | import org.springframework.web.filter.CorsFilter; 11 | 12 | /** 13 | * @author Administrator 14 | * @version 1.0 15 | **/ 16 | @Configuration 17 | public class ZuulConfig { 18 | 19 | @Bean 20 | public AuthFilter preFileter() { 21 | return new AuthFilter(); 22 | } 23 | 24 | @Bean 25 | public FilterRegistrationBean corsFilter() { 26 | final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); 27 | final CorsConfiguration config = new CorsConfiguration(); 28 | config.setAllowCredentials(true); 29 | config.addAllowedOrigin("*"); 30 | config.addAllowedHeader("*"); 31 | config.addAllowedMethod("*"); 32 | config.setMaxAge(18000L); 33 | source.registerCorsConfiguration("/**", config); 34 | CorsFilter corsFilter = new CorsFilter(source); 35 | FilterRegistrationBean bean = new FilterRegistrationBean(corsFilter); 36 | bean.setOrder(Ordered.HIGHEST_PRECEDENCE); 37 | return bean; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /distributed-security/distributed-security-gateway/src/main/java/com/pbteach/security/distributed/gateway/filter/AuthFilter.java: -------------------------------------------------------------------------------- 1 | package com.pbteach.security.distributed.gateway.filter; 2 | 3 | import com.alibaba.fastjson.JSON; 4 | import com.pbteach.security.distributed.gateway.common.EncryptUtil; 5 | import com.netflix.zuul.ZuulFilter; 6 | import com.netflix.zuul.context.RequestContext; 7 | import com.netflix.zuul.exception.ZuulException; 8 | import org.springframework.security.core.Authentication; 9 | import org.springframework.security.core.GrantedAuthority; 10 | import org.springframework.security.core.context.SecurityContextHolder; 11 | import org.springframework.security.oauth2.provider.OAuth2Authentication; 12 | import org.springframework.security.oauth2.provider.OAuth2Request; 13 | 14 | import java.util.ArrayList; 15 | import java.util.HashMap; 16 | import java.util.List; 17 | import java.util.Map; 18 | 19 | /** 20 | * @author Administrator 21 | * @version 1.0 22 | **/ 23 | public class AuthFilter extends ZuulFilter { 24 | 25 | @Override 26 | public boolean shouldFilter() { 27 | return true; 28 | } 29 | 30 | @Override 31 | public String filterType() { 32 | return "pre"; 33 | } 34 | 35 | @Override 36 | public int filterOrder() { 37 | return 0; 38 | } 39 | 40 | @Override 41 | public Object run() throws ZuulException { 42 | RequestContext ctx = RequestContext.getCurrentContext(); 43 | //从安全上下文中拿 到用户身份对象 44 | Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); 45 | if(!(authentication instanceof OAuth2Authentication)){ 46 | return null; 47 | } 48 | OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) authentication; 49 | Authentication userAuthentication = oAuth2Authentication.getUserAuthentication(); 50 | //取出用户身份信息 51 | String principal = userAuthentication.getName(); 52 | 53 | //取出用户权限 54 | List authorities = new ArrayList<>(); 55 | //从userAuthentication取出权限,放在authorities 56 | userAuthentication.getAuthorities().stream().forEach(c->authorities.add(((GrantedAuthority) c).getAuthority())); 57 | 58 | OAuth2Request oAuth2Request = oAuth2Authentication.getOAuth2Request(); 59 | Map requestParameters = oAuth2Request.getRequestParameters(); 60 | Map jsonToken = new HashMap<>(requestParameters); 61 | if(userAuthentication!=null){ 62 | jsonToken.put("principal",principal); 63 | jsonToken.put("authorities",authorities); 64 | } 65 | 66 | //把身份信息和权限信息放在json中,加入http的header中,转发给微服务 67 | ctx.addZuulRequestHeader("json-token", EncryptUtil.encodeUTF8StringBase64(JSON.toJSONString(jsonToken))); 68 | 69 | return null; 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /distributed-security/distributed-security-gateway/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.application.name=gateway-server 2 | server.port=53010 3 | spring.main.allow-bean-definition-overriding = true 4 | 5 | logging.level.root = info 6 | logging.level.org.springframework = info 7 | 8 | zuul.retryable = true 9 | zuul.ignoredServices = * 10 | zuul.add-host-header = true 11 | zuul.sensitiveHeaders = * 12 | 13 | zuul.routes.uaa-service.stripPrefix = false 14 | zuul.routes.uaa-service.path = /uaa/** 15 | 16 | zuul.routes.order-service.stripPrefix = false 17 | zuul.routes.order-service.path = /order/** 18 | 19 | eureka.client.serviceUrl.defaultZone = http://localhost:53000/eureka/ 20 | eureka.instance.preferIpAddress = true 21 | eureka.instance.instance-id = ${spring.application.name}:${spring.cloud.client.ip-address}:${spring.application.instance_id:${server.port}} 22 | management.endpoints.web.exposure.include = refresh,health,info,env 23 | 24 | feign.hystrix.enabled = true 25 | feign.compression.request.enabled = true 26 | feign.compression.request.mime-types[0] = text/xml 27 | feign.compression.request.mime-types[1] = application/xml 28 | feign.compression.request.mime-types[2] = application/json 29 | feign.compression.request.min-request-size = 2048 30 | feign.compression.response.enabled = true -------------------------------------------------------------------------------- /distributed-security/distributed-security-order/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | distributed-security 7 | com.pbteach.security 8 | 1.0-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | distributed-security-order 13 | 14 | 15 | 16 | org.springframework.cloud 17 | spring-cloud-starter-netflix-eureka-client 18 | 19 | 20 | 21 | org.springframework.boot 22 | spring-boot-starter-actuator 23 | 24 | 25 | 26 | org.springframework.boot 27 | spring-boot-starter-web 28 | 29 | 30 | 31 | org.springframework.cloud 32 | spring-cloud-starter-security 33 | 34 | 35 | org.springframework.cloud 36 | spring-cloud-starter-oauth2 37 | 38 | 39 | javax.interceptor 40 | javax.interceptor-api 41 | 42 | 43 | 44 | com.alibaba 45 | fastjson 46 | 47 | 48 | 49 | org.projectlombok 50 | lombok 51 | 52 | 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /distributed-security/distributed-security-order/src/main/java/com/pbteach/security/distributed/order/OrderServer.java: -------------------------------------------------------------------------------- 1 | package com.pbteach.security.distributed.order; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.cloud.client.discovery.EnableDiscoveryClient; 6 | 7 | /** 8 | * @author Administrator 9 | * @version 1.0 10 | **/ 11 | @SpringBootApplication 12 | @EnableDiscoveryClient 13 | public class OrderServer { 14 | public static void main(String[] args) { 15 | SpringApplication.run(OrderServer.class, args); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /distributed-security/distributed-security-order/src/main/java/com/pbteach/security/distributed/order/common/EncryptUtil.java: -------------------------------------------------------------------------------- 1 | package com.pbteach.security.distributed.order.common; 2 | 3 | 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | 7 | import java.io.UnsupportedEncodingException; 8 | import java.net.URLDecoder; 9 | import java.net.URLEncoder; 10 | import java.util.Base64; 11 | 12 | public class EncryptUtil { 13 | private static final Logger logger = LoggerFactory.getLogger(EncryptUtil.class); 14 | 15 | public static String encodeBase64(byte[] bytes){ 16 | String encoded = Base64.getEncoder().encodeToString(bytes); 17 | return encoded; 18 | } 19 | 20 | public static byte[] decodeBase64(String str){ 21 | byte[] bytes = null; 22 | bytes = Base64.getDecoder().decode(str); 23 | return bytes; 24 | } 25 | 26 | public static String encodeUTF8StringBase64(String str){ 27 | String encoded = null; 28 | try { 29 | encoded = Base64.getEncoder().encodeToString(str.getBytes("utf-8")); 30 | } catch (UnsupportedEncodingException e) { 31 | logger.warn("不支持的编码格式",e); 32 | } 33 | return encoded; 34 | 35 | } 36 | 37 | public static String decodeUTF8StringBase64(String str){ 38 | String decoded = null; 39 | byte[] bytes = Base64.getDecoder().decode(str); 40 | try { 41 | decoded = new String(bytes,"utf-8"); 42 | }catch(UnsupportedEncodingException e){ 43 | logger.warn("不支持的编码格式",e); 44 | } 45 | return decoded; 46 | } 47 | 48 | public static String encodeURL(String url) { 49 | String encoded = null; 50 | try { 51 | encoded = URLEncoder.encode(url, "utf-8"); 52 | } catch (UnsupportedEncodingException e) { 53 | logger.warn("URLEncode失败", e); 54 | } 55 | return encoded; 56 | } 57 | 58 | 59 | public static String decodeURL(String url) { 60 | String decoded = null; 61 | try { 62 | decoded = URLDecoder.decode(url, "utf-8"); 63 | } catch (UnsupportedEncodingException e) { 64 | logger.warn("URLDecode失败", e); 65 | } 66 | return decoded; 67 | } 68 | 69 | public static void main(String [] args){ 70 | String str = "abcd{'a':'b'}"; 71 | String encoded = EncryptUtil.encodeUTF8StringBase64(str); 72 | String decoded = EncryptUtil.decodeUTF8StringBase64(encoded); 73 | System.out.println(str); 74 | System.out.println(encoded); 75 | System.out.println(decoded); 76 | 77 | String url = "== wo"; 78 | String urlEncoded = EncryptUtil.encodeURL(url); 79 | String urlDecoded = EncryptUtil.decodeURL(urlEncoded); 80 | 81 | System.out.println(url); 82 | System.out.println(urlEncoded); 83 | System.out.println(urlDecoded); 84 | } 85 | 86 | 87 | } 88 | -------------------------------------------------------------------------------- /distributed-security/distributed-security-order/src/main/java/com/pbteach/security/distributed/order/config/ResouceServerConfig.java: -------------------------------------------------------------------------------- 1 | package com.pbteach.security.distributed.order.config; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 6 | import org.springframework.security.config.http.SessionCreationPolicy; 7 | import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; 8 | import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; 9 | import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; 10 | import org.springframework.security.oauth2.provider.token.TokenStore; 11 | 12 | /** 13 | * @author Administrator 14 | * @version 1.0 15 | **/ 16 | @Configuration 17 | @EnableResourceServer 18 | public class ResouceServerConfig extends ResourceServerConfigurerAdapter { 19 | 20 | 21 | public static final String RESOURCE_ID = "res1"; 22 | 23 | @Autowired 24 | TokenStore tokenStore; 25 | 26 | @Override 27 | public void configure(ResourceServerSecurityConfigurer resources) { 28 | resources.resourceId(RESOURCE_ID)//资源 id 29 | .tokenStore(tokenStore) 30 | // .tokenServices(tokenService())//验证令牌的服务 31 | .stateless(true); 32 | } 33 | 34 | @Override 35 | public void configure(HttpSecurity http) throws Exception { 36 | 37 | http 38 | .authorizeRequests() 39 | .antMatchers("/**").access("#oauth2.hasScope('ROLE_ADMIN')") 40 | .and().csrf().disable() 41 | .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); 42 | } 43 | 44 | //资源服务令牌解析服务 45 | /* @Bean 46 | public ResourceServerTokenServices tokenService() { 47 | //使用远程服务请求授权服务器校验token,必须指定校验token 的url、client_id,client_secret 48 | RemoteTokenServices service=new RemoteTokenServices(); 49 | service.setCheckTokenEndpointUrl("http://localhost:53020/uaa/oauth/check_token"); 50 | service.setClientId("c1"); 51 | service.setClientSecret("secret"); 52 | return service; 53 | }*/ 54 | 55 | } 56 | -------------------------------------------------------------------------------- /distributed-security/distributed-security-order/src/main/java/com/pbteach/security/distributed/order/config/TokenConfig.java: -------------------------------------------------------------------------------- 1 | package com.pbteach.security.distributed.order.config; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.security.oauth2.provider.token.TokenStore; 6 | import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; 7 | import org.springframework.security.oauth2.provider.token.store.JwtTokenStore; 8 | 9 | /** 10 | * @author Administrator 11 | * @version 1.0 12 | **/ 13 | @Configuration 14 | public class TokenConfig { 15 | 16 | private String SIGNING_KEY = "uaa123"; 17 | 18 | @Bean 19 | public TokenStore tokenStore() { 20 | //JWT令牌存储方案 21 | return new JwtTokenStore(accessTokenConverter()); 22 | } 23 | 24 | @Bean 25 | public JwtAccessTokenConverter accessTokenConverter() { 26 | JwtAccessTokenConverter converter = new JwtAccessTokenConverter(); 27 | converter.setSigningKey(SIGNING_KEY); //对称秘钥,资源服务器使用该秘钥来验证 28 | return converter; 29 | } 30 | 31 | /* @Bean 32 | public TokenStore tokenStore() { 33 | //使用内存存储令牌(普通令牌) 34 | return new InMemoryTokenStore(); 35 | }*/ 36 | } 37 | -------------------------------------------------------------------------------- /distributed-security/distributed-security-order/src/main/java/com/pbteach/security/distributed/order/config/WebSecurityConfig.java: -------------------------------------------------------------------------------- 1 | package com.pbteach.security.distributed.order.config; 2 | 3 | import org.springframework.context.annotation.Configuration; 4 | import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; 5 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 6 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 7 | 8 | /** 9 | * @author Administrator 10 | * @version 1.0 11 | **/ 12 | @Configuration 13 | @EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true) 14 | public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 15 | 16 | 17 | //安全拦截机制(最重要) 18 | @Override 19 | protected void configure(HttpSecurity http) throws Exception { 20 | http.csrf().disable() 21 | .authorizeRequests() 22 | // .antMatchers("/r/r1").hasAuthority("p2") 23 | // .antMatchers("/r/r2").hasAuthority("p2") 24 | .antMatchers("/r/**").authenticated()//所有/r/**的请求必须认证通过 25 | .anyRequest().permitAll()//除了/r/**,其它的请求可以访问 26 | ; 27 | 28 | 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /distributed-security/distributed-security-order/src/main/java/com/pbteach/security/distributed/order/controller/OrderController.java: -------------------------------------------------------------------------------- 1 | package com.pbteach.security.distributed.order.controller; 2 | 3 | import com.pbteach.security.distributed.order.model.UserDTO; 4 | import org.springframework.security.access.prepost.PreAuthorize; 5 | import org.springframework.security.core.context.SecurityContextHolder; 6 | import org.springframework.web.bind.annotation.GetMapping; 7 | import org.springframework.web.bind.annotation.RestController; 8 | 9 | /** 10 | * @author Administrator 11 | * @version 1.0 12 | **/ 13 | @RestController 14 | public class OrderController { 15 | 16 | @GetMapping(value = "/r1") 17 | @PreAuthorize("hasAuthority('p1')")//拥有p1权限方可访问此url 18 | public String r1(){ 19 | //获取用户身份信息 20 | UserDTO userDTO = (UserDTO) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); 21 | return userDTO.getFullname()+"访问资源1"; 22 | } 23 | 24 | } -------------------------------------------------------------------------------- /distributed-security/distributed-security-order/src/main/java/com/pbteach/security/distributed/order/filter/TokenAuthenticationFilter.java: -------------------------------------------------------------------------------- 1 | package com.pbteach.security.distributed.order.filter; 2 | 3 | import com.alibaba.fastjson.JSON; 4 | import com.alibaba.fastjson.JSONArray; 5 | import com.alibaba.fastjson.JSONObject; 6 | import com.pbteach.security.distributed.order.common.EncryptUtil; 7 | import com.pbteach.security.distributed.order.model.UserDTO; 8 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 9 | import org.springframework.security.core.authority.AuthorityUtils; 10 | import org.springframework.security.core.context.SecurityContextHolder; 11 | import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; 12 | import org.springframework.stereotype.Component; 13 | import org.springframework.web.filter.OncePerRequestFilter; 14 | 15 | import javax.servlet.FilterChain; 16 | import javax.servlet.ServletException; 17 | import javax.servlet.http.HttpServletRequest; 18 | import javax.servlet.http.HttpServletResponse; 19 | import java.io.IOException; 20 | 21 | /** 22 | * @author Administrator 23 | * @version 1.0 24 | **/ 25 | @Component 26 | public class TokenAuthenticationFilter extends OncePerRequestFilter { 27 | 28 | 29 | @Override 30 | protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException { 31 | //解析出头中的token 32 | String token = httpServletRequest.getHeader("json-token"); 33 | if(token!=null){ 34 | String json = EncryptUtil.decodeUTF8StringBase64(token); 35 | //将token转成json对象 36 | JSONObject jsonObject = JSON.parseObject(json); 37 | //用户身份信息 38 | // UserDTO userDTO = new UserDTO(); 39 | // String principal = jsonObject.getString("principal"); 40 | // userDTO.setUsername(principal); 41 | UserDTO userDTO = JSON.parseObject(jsonObject.getString("principal"), UserDTO.class); 42 | //用户权限 43 | JSONArray authoritiesArray = jsonObject.getJSONArray("authorities"); 44 | String[] authorities = authoritiesArray.toArray(new String[authoritiesArray.size()]); 45 | //将用户信息和权限填充 到用户身份token对象中 46 | UsernamePasswordAuthenticationToken authenticationToken 47 | = new UsernamePasswordAuthenticationToken(userDTO,null, AuthorityUtils.createAuthorityList(authorities)); 48 | authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest)); 49 | //将authenticationToken填充到安全上下文 50 | SecurityContextHolder.getContext().setAuthentication(authenticationToken); 51 | 52 | 53 | } 54 | filterChain.doFilter(httpServletRequest,httpServletResponse); 55 | 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /distributed-security/distributed-security-order/src/main/java/com/pbteach/security/distributed/order/model/UserDTO.java: -------------------------------------------------------------------------------- 1 | package com.pbteach.security.distributed.order.model; 2 | 3 | import lombok.Data; 4 | 5 | /** 6 | * 用户信息 7 | */ 8 | @Data 9 | public class UserDTO { 10 | 11 | /** 12 | * 用户id 13 | */ 14 | private String id; 15 | /** 16 | * 用户名 17 | */ 18 | private String username; 19 | 20 | /** 21 | * 手机号 22 | */ 23 | private String mobile; 24 | 25 | /** 26 | * 姓名 27 | */ 28 | private String fullname; 29 | 30 | 31 | 32 | 33 | } 34 | -------------------------------------------------------------------------------- /distributed-security/distributed-security-order/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.application.name=order-service 2 | server.port=53021 3 | spring.main.allow-bean-definition-overriding = true 4 | 5 | logging.level.root = debug 6 | logging.level.org.springframework.web = info 7 | spring.http.encoding.enabled = true 8 | spring.http.encoding.charset = UTF-8 9 | spring.http.encoding.force = true 10 | server.tomcat.remote_ip_header = x-forwarded-for 11 | server.tomcat.protocol_header = x-forwarded-proto 12 | server.use-forward-headers = true 13 | server.servlet.context-path = /order 14 | 15 | 16 | spring.freemarker.enabled = true 17 | spring.freemarker.suffix = .html 18 | spring.freemarker.request-context-attribute = rc 19 | spring.freemarker.content-type = text/html 20 | spring.freemarker.charset = UTF-8 21 | spring.mvc.throw-exception-if-no-handler-found = true 22 | spring.resources.add-mappings = false 23 | 24 | 25 | eureka.client.serviceUrl.defaultZone = http://localhost:53000/eureka/ 26 | eureka.instance.preferIpAddress = true 27 | eureka.instance.instance-id = ${spring.application.name}:${spring.cloud.client.ip-address}:${spring.application.instance_id:${server.port}} 28 | management.endpoints.web.exposure.include = refresh,health,info,env 29 | 30 | feign.hystrix.enabled = true 31 | feign.compression.request.enabled = true 32 | feign.compression.request.mime-types[0] = text/xml 33 | feign.compression.request.mime-types[1] = application/xml 34 | feign.compression.request.mime-types[2] = application/json 35 | feign.compression.request.min-request-size = 2048 36 | feign.compression.response.enabled = true -------------------------------------------------------------------------------- /distributed-security/distributed-security-uaa/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | distributed-security 7 | com.pbteach.security 8 | 1.0-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | distributed-security-uaa 13 | 14 | 15 | 16 | 17 | org.springframework.cloud 18 | spring-cloud-starter-netflix-eureka-client 19 | 20 | 21 | 22 | org.springframework.cloud 23 | spring-cloud-starter-netflix-hystrix 24 | 25 | 26 | 27 | org.springframework.cloud 28 | spring-cloud-starter-netflix-ribbon 29 | 30 | 31 | 32 | org.springframework.cloud 33 | spring-cloud-starter-openfeign 34 | 35 | 36 | 37 | com.netflix.hystrix 38 | hystrix-javanica 39 | 40 | 41 | 42 | org.springframework.retry 43 | spring-retry 44 | 45 | 46 | 47 | org.springframework.boot 48 | spring-boot-starter-actuator 49 | 50 | 51 | 52 | 53 | org.springframework.boot 54 | spring-boot-starter-web 55 | 56 | 57 | 58 | org.springframework.boot 59 | spring-boot-starter-freemarker 60 | 61 | 62 | 63 | 64 | org.springframework.data 65 | spring-data-commons 66 | 67 | 68 | 69 | org.springframework.cloud 70 | spring-cloud-starter-security 71 | 72 | 73 | 74 | org.springframework.cloud 75 | spring-cloud-starter-oauth2 76 | 77 | 78 | 79 | org.springframework.security 80 | spring-security-jwt 81 | 82 | 83 | 84 | javax.interceptor 85 | javax.interceptor-api 86 | 87 | 88 | 89 | mysql 90 | mysql-connector-java 91 | 92 | 93 | org.springframework.boot 94 | spring-boot-starter-jdbc 95 | 96 | 97 | 98 | 99 | com.alibaba 100 | fastjson 101 | 102 | 103 | 104 | org.projectlombok 105 | lombok 106 | 107 | 108 | 109 | 110 | 111 | -------------------------------------------------------------------------------- /distributed-security/distributed-security-uaa/src/main/java/com/pbteach/security/distributed/uaa/UAAServer.java: -------------------------------------------------------------------------------- 1 | package com.pbteach.security.distributed.uaa; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.cloud.client.discovery.EnableDiscoveryClient; 6 | import org.springframework.cloud.netflix.hystrix.EnableHystrix; 7 | import org.springframework.cloud.openfeign.EnableFeignClients; 8 | 9 | /** 10 | * @author Administrator 11 | * @version 1.0 12 | **/ 13 | @SpringBootApplication 14 | @EnableDiscoveryClient 15 | @EnableHystrix 16 | @EnableFeignClients(basePackages = {"com.pbteach.security.distributed.uaa"}) 17 | public class UAAServer { 18 | public static void main(String[] args) { 19 | SpringApplication.run(UAAServer.class, args); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /distributed-security/distributed-security-uaa/src/main/java/com/pbteach/security/distributed/uaa/config/AuthorizationServer.java: -------------------------------------------------------------------------------- 1 | package com.pbteach.security.distributed.uaa.config; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.http.HttpMethod; 7 | import org.springframework.security.authentication.AuthenticationManager; 8 | import org.springframework.security.crypto.password.PasswordEncoder; 9 | import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; 10 | import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; 11 | import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; 12 | import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; 13 | import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; 14 | import org.springframework.security.oauth2.provider.ClientDetailsService; 15 | import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService; 16 | import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices; 17 | import org.springframework.security.oauth2.provider.code.JdbcAuthorizationCodeServices; 18 | import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices; 19 | import org.springframework.security.oauth2.provider.token.DefaultTokenServices; 20 | import org.springframework.security.oauth2.provider.token.TokenEnhancerChain; 21 | import org.springframework.security.oauth2.provider.token.TokenStore; 22 | import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; 23 | 24 | import javax.sql.DataSource; 25 | import java.util.Arrays; 26 | 27 | /** 28 | * @author Administrator 29 | * @version 1.0 30 | * 授权服务配置 31 | **/ 32 | @Configuration 33 | @EnableAuthorizationServer 34 | public class AuthorizationServer extends AuthorizationServerConfigurerAdapter { 35 | 36 | @Autowired 37 | private TokenStore tokenStore; 38 | 39 | @Autowired 40 | private ClientDetailsService clientDetailsService; 41 | 42 | @Autowired 43 | private AuthorizationCodeServices authorizationCodeServices; 44 | 45 | @Autowired 46 | private AuthenticationManager authenticationManager; 47 | 48 | @Autowired 49 | private JwtAccessTokenConverter accessTokenConverter; 50 | 51 | @Autowired 52 | PasswordEncoder passwordEncoder; 53 | 54 | //将客户端信息存储到数据库 55 | @Bean 56 | public ClientDetailsService clientDetailsService(DataSource dataSource) { 57 | ClientDetailsService clientDetailsService = new JdbcClientDetailsService(dataSource); 58 | ((JdbcClientDetailsService) clientDetailsService).setPasswordEncoder(passwordEncoder); 59 | return clientDetailsService; 60 | } 61 | 62 | //客户端详情服务 63 | @Override 64 | public void configure(ClientDetailsServiceConfigurer clients) 65 | throws Exception { 66 | clients.withClientDetails(clientDetailsService); 67 | /* clients.inMemory()// 使用in-memory存储 68 | .withClient("c1")// client_id 69 | .secret(new BCryptPasswordEncoder().encode("secret"))//客户端密钥 70 | .resourceIds("res1")//资源列表 71 | .authorizedGrantTypes("authorization_code", "password","client_credentials","implicit","refresh_token")// 该client允许的授权类型authorization_code,password,refresh_token,implicit,client_credentials 72 | .scopes("all")// 允许的授权范围 73 | .autoApprove(false)//false跳转到授权页面 74 | //加上验证回调地址 75 | .redirectUris("http://www.baidu.com")*/ 76 | ; 77 | } 78 | 79 | 80 | //令牌管理服务 81 | @Bean 82 | public AuthorizationServerTokenServices tokenService() { 83 | DefaultTokenServices service=new DefaultTokenServices(); 84 | service.setClientDetailsService(clientDetailsService);//客户端详情服务 85 | service.setSupportRefreshToken(true);//支持刷新令牌 86 | service.setTokenStore(tokenStore);//令牌存储策略 87 | //令牌增强 88 | TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain(); 89 | tokenEnhancerChain.setTokenEnhancers(Arrays.asList(accessTokenConverter)); 90 | service.setTokenEnhancer(tokenEnhancerChain); 91 | 92 | service.setAccessTokenValiditySeconds(7200); // 令牌默认有效期2小时 93 | service.setRefreshTokenValiditySeconds(259200); // 刷新令牌默认有效期3天 94 | return service; 95 | } 96 | 97 | //设置授权码模式的授权码如何存取,暂时采用内存方式 98 | /* @Bean 99 | public AuthorizationCodeServices authorizationCodeServices() { 100 | return new InMemoryAuthorizationCodeServices(); 101 | }*/ 102 | 103 | @Bean 104 | public AuthorizationCodeServices authorizationCodeServices(DataSource dataSource) { 105 | return new JdbcAuthorizationCodeServices(dataSource);//设置授权码模式的授权码如何存取 106 | } 107 | 108 | @Override 109 | public void configure(AuthorizationServerEndpointsConfigurer endpoints) { 110 | endpoints 111 | .authenticationManager(authenticationManager)//认证管理器 112 | .authorizationCodeServices(authorizationCodeServices)//授权码服务 113 | .tokenServices(tokenService())//令牌管理服务 114 | .allowedTokenEndpointRequestMethods(HttpMethod.POST); 115 | } 116 | 117 | @Override 118 | public void configure(AuthorizationServerSecurityConfigurer security){ 119 | security 120 | .tokenKeyAccess("permitAll()") //oauth/token_key是公开 121 | .checkTokenAccess("permitAll()") //oauth/check_token公开 122 | .allowFormAuthenticationForClients() //表单认证(申请令牌) 123 | ; 124 | } 125 | 126 | } 127 | -------------------------------------------------------------------------------- /distributed-security/distributed-security-uaa/src/main/java/com/pbteach/security/distributed/uaa/config/TokenConfig.java: -------------------------------------------------------------------------------- 1 | package com.pbteach.security.distributed.uaa.config; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.security.oauth2.provider.token.TokenStore; 6 | import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; 7 | import org.springframework.security.oauth2.provider.token.store.JwtTokenStore; 8 | 9 | /** 10 | * @author Administrator 11 | * @version 1.0 12 | **/ 13 | @Configuration 14 | public class TokenConfig { 15 | 16 | private String SIGNING_KEY = "uaa123"; 17 | 18 | @Bean 19 | public TokenStore tokenStore() { 20 | //JWT令牌存储方案 21 | return new JwtTokenStore(accessTokenConverter()); 22 | } 23 | 24 | @Bean 25 | public JwtAccessTokenConverter accessTokenConverter() { 26 | JwtAccessTokenConverter converter = new JwtAccessTokenConverter(); 27 | converter.setSigningKey(SIGNING_KEY); //对称秘钥,资源服务器使用该秘钥来验证 28 | return converter; 29 | } 30 | 31 | /* @Bean 32 | public TokenStore tokenStore() { 33 | //使用内存存储令牌(普通令牌) 34 | return new InMemoryTokenStore(); 35 | }*/ 36 | } 37 | -------------------------------------------------------------------------------- /distributed-security/distributed-security-uaa/src/main/java/com/pbteach/security/distributed/uaa/config/WebSecurityConfig.java: -------------------------------------------------------------------------------- 1 | package com.pbteach.security.distributed.uaa.config; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.security.authentication.AuthenticationManager; 6 | import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; 7 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 8 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 9 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 10 | import org.springframework.security.crypto.password.PasswordEncoder; 11 | 12 | /** 13 | * @author Administrator 14 | * @version 1.0 15 | **/ 16 | @Configuration 17 | @EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true) 18 | public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 19 | 20 | //认证管理器 21 | @Bean 22 | public AuthenticationManager authenticationManagerBean() throws Exception { 23 | return super.authenticationManagerBean(); 24 | } 25 | //密码编码器 26 | @Bean 27 | public PasswordEncoder passwordEncoder() { 28 | return new BCryptPasswordEncoder(); 29 | } 30 | 31 | //安全拦截机制(最重要) 32 | @Override 33 | protected void configure(HttpSecurity http) throws Exception { 34 | http.csrf().disable() 35 | .authorizeRequests() 36 | .antMatchers("/r/r1").hasAnyAuthority("p1") 37 | .antMatchers("/login*").permitAll() 38 | .anyRequest().authenticated() 39 | .and() 40 | .formLogin() 41 | ; 42 | 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /distributed-security/distributed-security-uaa/src/main/java/com/pbteach/security/distributed/uaa/dao/UserDao.java: -------------------------------------------------------------------------------- 1 | package com.pbteach.security.distributed.uaa.dao; 2 | 3 | import com.pbteach.security.distributed.uaa.model.PermissionDto; 4 | import com.pbteach.security.distributed.uaa.model.UserDto; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.jdbc.core.BeanPropertyRowMapper; 7 | import org.springframework.jdbc.core.JdbcTemplate; 8 | import org.springframework.stereotype.Repository; 9 | 10 | import java.util.ArrayList; 11 | import java.util.List; 12 | 13 | /** 14 | * @author Administrator 15 | * @version 1.0 16 | **/ 17 | @Repository 18 | public class UserDao { 19 | 20 | @Autowired 21 | JdbcTemplate jdbcTemplate; 22 | 23 | //根据账号查询用户信息 24 | public UserDto getUserByUsername(String username){ 25 | String sql = "select id,username,password,fullname,mobile from t_user where username = ?"; 26 | //连接数据库查询用户 27 | List list = jdbcTemplate.query(sql, new Object[]{username}, new BeanPropertyRowMapper<>(UserDto.class)); 28 | if(list !=null && list.size()==1){ 29 | return list.get(0); 30 | } 31 | return null; 32 | } 33 | 34 | //根据用户id查询用户权限 35 | public List findPermissionsByUserId(String userId){ 36 | String sql = "SELECT * FROM t_permission WHERE id IN(\n" + 37 | "\n" + 38 | "SELECT permission_id FROM t_role_permission WHERE role_id IN(\n" + 39 | " SELECT role_id FROM t_user_role WHERE user_id = ? \n" + 40 | ")\n" + 41 | ")\n"; 42 | 43 | List list = jdbcTemplate.query(sql, new Object[]{userId}, new BeanPropertyRowMapper<>(PermissionDto.class)); 44 | List permissions = new ArrayList<>(); 45 | list.forEach(c -> permissions.add(c.getCode())); 46 | return permissions; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /distributed-security/distributed-security-uaa/src/main/java/com/pbteach/security/distributed/uaa/model/PermissionDto.java: -------------------------------------------------------------------------------- 1 | package com.pbteach.security.distributed.uaa.model; 2 | 3 | import lombok.Data; 4 | 5 | /** 6 | * @author Administrator 7 | * @version 1.0 8 | **/ 9 | @Data 10 | public class PermissionDto { 11 | 12 | private String id; 13 | private String code; 14 | private String description; 15 | private String url; 16 | } 17 | -------------------------------------------------------------------------------- /distributed-security/distributed-security-uaa/src/main/java/com/pbteach/security/distributed/uaa/model/UserDto.java: -------------------------------------------------------------------------------- 1 | package com.pbteach.security.distributed.uaa.model; 2 | 3 | import lombok.Data; 4 | 5 | /** 6 | * @author Administrator 7 | * @version 1.0 8 | **/ 9 | @Data 10 | public class UserDto { 11 | private String id; 12 | private String username; 13 | private String password; 14 | private String fullname; 15 | private String mobile; 16 | } 17 | -------------------------------------------------------------------------------- /distributed-security/distributed-security-uaa/src/main/java/com/pbteach/security/distributed/uaa/service/SpringDataUserDetailsService.java: -------------------------------------------------------------------------------- 1 | package com.pbteach.security.distributed.uaa.service; 2 | 3 | import com.alibaba.fastjson.JSON; 4 | import com.pbteach.security.distributed.uaa.dao.UserDao; 5 | import com.pbteach.security.distributed.uaa.model.UserDto; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.security.core.userdetails.User; 8 | import org.springframework.security.core.userdetails.UserDetails; 9 | import org.springframework.security.core.userdetails.UserDetailsService; 10 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 11 | import org.springframework.stereotype.Service; 12 | 13 | import java.util.List; 14 | 15 | /** 16 | * @author Administrator 17 | * @version 1.0 18 | **/ 19 | @Service 20 | public class SpringDataUserDetailsService implements UserDetailsService { 21 | 22 | @Autowired 23 | UserDao userDao; 24 | 25 | //根据 账号查询用户信息 26 | @Override 27 | public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { 28 | 29 | //将来连接数据库根据账号查询用户信息 30 | UserDto userDto = userDao.getUserByUsername(username); 31 | if(userDto == null){ 32 | //如果用户查不到,返回null,由provider来抛出异常 33 | return null; 34 | } 35 | //根据用户的id查询用户的权限 36 | List permissions = userDao.findPermissionsByUserId(userDto.getId()); 37 | //将permissions转成数组 38 | String[] permissionArray = new String[permissions.size()]; 39 | permissions.toArray(permissionArray); 40 | //将userDto转成json 41 | String principal = JSON.toJSONString(userDto); 42 | UserDetails userDetails = User.withUsername(principal).password(userDto.getPassword()).authorities(permissionArray).build(); 43 | return userDetails; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /distributed-security/distributed-security-uaa/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.application.name=uaa-service 2 | server.port=53020 3 | spring.main.allow-bean-definition-overriding = true 4 | 5 | logging.level.root = debug 6 | logging.level.org.springframework.web = info 7 | 8 | spring.http.encoding.enabled = true 9 | spring.http.encoding.charset = UTF-8 10 | spring.http.encoding.force = true 11 | server.tomcat.remote_ip_header = x-forwarded-for 12 | server.tomcat.protocol_header = x-forwarded-proto 13 | server.use-forward-headers = true 14 | server.servlet.context-path = /uaa 15 | 16 | spring.freemarker.enabled = true 17 | spring.freemarker.suffix = .html 18 | spring.freemarker.request-context-attribute = rc 19 | spring.freemarker.content-type = text/html 20 | spring.freemarker.charset = UTF-8 21 | spring.mvc.throw-exception-if-no-handler-found = true 22 | spring.resources.add-mappings = false 23 | 24 | spring.datasource.url = jdbc:mysql://localhost:3306/user_db?useUnicode=true 25 | spring.datasource.username = root 26 | spring.datasource.password = mysql 27 | spring.datasource.driver-class-name = com.mysql.jdbc.Driver 28 | 29 | eureka.client.serviceUrl.defaultZone = http://localhost:53000/eureka/ 30 | eureka.instance.preferIpAddress = true 31 | eureka.instance.instance-id = ${spring.application.name}:${spring.cloud.client.ip-address}:${spring.application.instance_id:${server.port}} 32 | management.endpoints.web.exposure.include = refresh,health,info,env 33 | 34 | feign.hystrix.enabled = true 35 | feign.compression.request.enabled = true 36 | feign.compression.request.mime-types[0] = text/xml 37 | feign.compression.request.mime-types[1] = application/xml 38 | feign.compression.request.mime-types[2] = application/json 39 | feign.compression.request.min-request-size = 2048 40 | feign.compression.response.enabled = true -------------------------------------------------------------------------------- /distributed-security/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.pbteach.security 8 | distributed-security 9 | 1.0-SNAPSHOT 10 | 11 | pom 12 | 13 | 14 | org.springframework.boot 15 | spring-boot-starter-parent 16 | 2.1.3.RELEASE 17 | 18 | 19 | 20 | UTF-8 21 | UTF-8 22 | 1.8 23 | 24 | 25 | 26 | 27 | 28 | 29 | org.springframework.cloud 30 | spring-cloud-dependencies 31 | Greenwich.RELEASE 32 | pom 33 | import 34 | 35 | 36 | 37 | 38 | javax.servlet 39 | javax.servlet-api 40 | 3.1.0 41 | provided 42 | 43 | 44 | 45 | javax.interceptor 46 | javax.interceptor-api 47 | 1.2 48 | 49 | 50 | 51 | com.alibaba 52 | fastjson 53 | 1.2.47 54 | 55 | 56 | 57 | org.projectlombok 58 | lombok 59 | 1.18.0 60 | 61 | 62 | 63 | mysql 64 | mysql-connector-java 65 | 5.1.47 66 | 67 | 68 | 69 | 70 | org.springframework.security 71 | spring-security-jwt 72 | 1.0.10.RELEASE 73 | 74 | 75 | 76 | 77 | org.springframework.security.oauth.boot 78 | spring-security-oauth2-autoconfigure 79 | 2.1.3.RELEASE 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | ${project.name} 90 | 91 | 92 | src/main/resources 93 | true 94 | 95 | **/* 96 | 97 | 98 | 99 | src/main/java 100 | 101 | **/*.xml 102 | 103 | 104 | 105 | 106 | 110 | 111 | 112 | org.apache.maven.plugins 113 | maven-compiler-plugin 114 | 115 | 1.8 116 | 1.8 117 | 118 | 119 | 120 | 121 | maven-resources-plugin 122 | 123 | utf-8 124 | true 125 | 126 | 127 | 128 | 129 | 130 | -------------------------------------------------------------------------------- /security-spring-boot/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.pbteach.security 8 | security-springboot 9 | 1.0-SNAPSHOT 10 | 11 | 12 | org.springframework.boot 13 | spring-boot-starter-parent 14 | 2.1.3.RELEASE 15 | 16 | 17 | 18 | UTF-8 19 | 1.8 20 | 1.8 21 | 22 | 23 | 24 | 25 | org.springframework.boot 26 | spring-boot-starter-web 27 | 28 | 29 | 30 | 31 | org.springframework.boot 32 | spring-boot-starter-security 33 | 34 | 35 | 36 | 37 | 38 | javax.servlet 39 | javax.servlet-api 40 | provided 41 | 42 | 43 | 44 | javax.servlet 45 | jstl 46 | 47 | 48 | 49 | org.springframework.boot 50 | spring-boot-starter-tomcat 51 | provided 52 | 53 | 54 | 55 | org.apache.tomcat.embed 56 | tomcat-embed-jasper 57 | provided 58 | 59 | 60 | org.projectlombok 61 | lombok 62 | 1.18.0 63 | 64 | 65 | org.springframework.boot 66 | spring-boot-starter-test 67 | test 68 | 69 | 70 | 71 | org.springframework.boot 72 | spring-boot-starter-jdbc 73 | 74 | 75 | 76 | mysql 77 | mysql-connector-java 78 | 5.1.47 79 | 80 | 81 | 82 | security-springboot 83 | 84 | 85 | 86 | org.apache.tomcat.maven 87 | tomcat7-maven-plugin 88 | 2.2 89 | 90 | 91 | org.apache.maven.plugins 92 | maven-compiler-plugin 93 | 94 | 1.8 95 | 1.8 96 | 97 | 98 | 99 | 100 | maven-resources-plugin 101 | 102 | utf-8 103 | true 104 | 105 | 106 | src/main/resources 107 | true 108 | 109 | **/* 110 | 111 | 112 | 113 | src/main/java 114 | 115 | **/*.xml 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | -------------------------------------------------------------------------------- /security-spring-boot/src/main/java/com/pbteach/security/springboot/SecuritySpringBootApp.java: -------------------------------------------------------------------------------- 1 | package com.pbteach.security.springboot; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | /** 7 | * @author Administrator 8 | * @version 1.0 9 | **/ 10 | @SpringBootApplication 11 | public class SecuritySpringBootApp { 12 | public static void main(String[] args) { 13 | SpringApplication.run(SecuritySpringBootApp.class,args); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /security-spring-boot/src/main/java/com/pbteach/security/springboot/config/WebConfig.java: -------------------------------------------------------------------------------- 1 | package com.pbteach.security.springboot.config; 2 | 3 | import org.springframework.context.annotation.Configuration; 4 | import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; 5 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 6 | 7 | /** 8 | * @author Administrator 9 | * @version 1.0 10 | **/ 11 | @Configuration//就相当于springmvc.xml文件 12 | public class WebConfig implements WebMvcConfigurer { 13 | 14 | 15 | @Override 16 | public void addViewControllers(ViewControllerRegistry registry) { 17 | registry.addViewController("/").setViewName("redirect:/login-view"); 18 | registry.addViewController("/login-view").setViewName("login"); 19 | 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /security-spring-boot/src/main/java/com/pbteach/security/springboot/config/WebSecurityConfig.java: -------------------------------------------------------------------------------- 1 | package com.pbteach.security.springboot.config; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; 6 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 7 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 8 | import org.springframework.security.config.http.SessionCreationPolicy; 9 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 10 | import org.springframework.security.crypto.password.PasswordEncoder; 11 | 12 | /** 13 | * @author Administrator 14 | * @version 1.0 15 | **/ 16 | @Configuration 17 | @EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true) 18 | public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 19 | 20 | //定义用户信息服务(查询用户信息) 21 | /* 22 | @Bean 23 | public UserDetailsService userDetailsService(){ 24 | InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager(); 25 | manager.createUser(User.withUsername("zhangsan").password("123").authorities("p1").build()); 26 | manager.createUser(User.withUsername("lisi").password("456").authorities("p2").build()); 27 | return manager; 28 | } 29 | */ 30 | 31 | //密码编码器 32 | /*@Bean 33 | public PasswordEncoder passwordEncoder(){ 34 | return NoOpPasswordEncoder.getInstance(); 35 | }*/ 36 | @Bean 37 | public PasswordEncoder passwordEncoder() { 38 | return new BCryptPasswordEncoder(); 39 | } 40 | 41 | //安全拦截机制(最重要) 42 | @Override 43 | protected void configure(HttpSecurity http) throws Exception { 44 | http.csrf().disable() 45 | .authorizeRequests() 46 | // .antMatchers("/r/r1").hasAuthority("p2") 47 | // .antMatchers("/r/r2").hasAuthority("p2") 48 | .antMatchers("/r/**").authenticated()//所有/r/**的请求必须认证通过 49 | .anyRequest().permitAll()//除了/r/**,其它的请求可以访问 50 | .and() 51 | .formLogin()//允许表单登录 52 | .loginPage("/login-view")//登录页面 53 | .loginProcessingUrl("/login") 54 | .successForwardUrl("/login-success")//自定义登录成功的页面地址 55 | .and() 56 | .sessionManagement() 57 | .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) 58 | .and() 59 | .logout() 60 | .logoutUrl("/logout") 61 | .logoutSuccessUrl("/login-view?logout"); 62 | 63 | 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /security-spring-boot/src/main/java/com/pbteach/security/springboot/controller/LoginController.java: -------------------------------------------------------------------------------- 1 | package com.pbteach.security.springboot.controller; 2 | 3 | import org.springframework.security.access.prepost.PreAuthorize; 4 | import org.springframework.security.core.Authentication; 5 | import org.springframework.security.core.context.SecurityContextHolder; 6 | import org.springframework.security.core.userdetails.UserDetails; 7 | import org.springframework.web.bind.annotation.GetMapping; 8 | import org.springframework.web.bind.annotation.RequestMapping; 9 | import org.springframework.web.bind.annotation.RestController; 10 | 11 | /** 12 | * @author Administrator 13 | * @version 1.0 14 | **/ 15 | @RestController 16 | public class LoginController { 17 | 18 | @RequestMapping(value = "/login-success",produces = {"text/plain;charset=UTF-8"}) 19 | public String loginSuccess(){ 20 | //提示具体用户名称登录成功 21 | return getUsername()+" 登录成功"; 22 | } 23 | 24 | /** 25 | * 测试资源1 26 | * @return 27 | */ 28 | @GetMapping(value = "/r/r1",produces = {"text/plain;charset=UTF-8"}) 29 | @PreAuthorize("hasAuthority('p1')")//拥有p1权限才可以访问 30 | public String r1(){ 31 | return getUsername()+" 访问资源1"; 32 | } 33 | 34 | /** 35 | * 测试资源2 36 | * @return 37 | */ 38 | @GetMapping(value = "/r/r2",produces = {"text/plain;charset=UTF-8"}) 39 | @PreAuthorize("hasAuthority('p2')")//拥有p2权限才可以访问 40 | public String r2(){ 41 | return getUsername()+" 访问资源2"; 42 | } 43 | 44 | //获取当前用户信息 45 | private String getUsername(){ 46 | String username = null; 47 | //当前认证通过的用户身份 48 | Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); 49 | //用户身份 50 | Object principal = authentication.getPrincipal(); 51 | if(principal == null){ 52 | username = "匿名"; 53 | } 54 | if(principal instanceof org.springframework.security.core.userdetails.UserDetails){ 55 | UserDetails userDetails = (UserDetails) principal; 56 | username = userDetails.getUsername(); 57 | }else{ 58 | username = principal.toString(); 59 | } 60 | return username; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /security-spring-boot/src/main/java/com/pbteach/security/springboot/dao/UserDao.java: -------------------------------------------------------------------------------- 1 | package com.pbteach.security.springboot.dao; 2 | 3 | import com.pbteach.security.springboot.model.PermissionDto; 4 | import com.pbteach.security.springboot.model.UserDto; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.jdbc.core.BeanPropertyRowMapper; 7 | import org.springframework.jdbc.core.JdbcTemplate; 8 | import org.springframework.stereotype.Repository; 9 | 10 | import java.util.ArrayList; 11 | import java.util.List; 12 | 13 | /** 14 | * @author Administrator 15 | * @version 1.0 16 | **/ 17 | @Repository 18 | public class UserDao { 19 | 20 | @Autowired 21 | JdbcTemplate jdbcTemplate; 22 | 23 | //根据账号查询用户信息 24 | public UserDto getUserByUsername(String username){ 25 | String sql = "select id,username,password,fullname,mobile from t_user where username = ?"; 26 | //连接数据库查询用户 27 | List list = jdbcTemplate.query(sql, new Object[]{username}, new BeanPropertyRowMapper<>(UserDto.class)); 28 | if(list !=null && list.size()==1){ 29 | return list.get(0); 30 | } 31 | return null; 32 | } 33 | 34 | //根据用户id查询用户权限 35 | public List findPermissionsByUserId(String userId){ 36 | String sql = "SELECT * FROM t_permission WHERE id IN(\n" + 37 | "\n" + 38 | "SELECT permission_id FROM t_role_permission WHERE role_id IN(\n" + 39 | " SELECT role_id FROM t_user_role WHERE user_id = ? \n" + 40 | ")\n" + 41 | ")\n"; 42 | 43 | List list = jdbcTemplate.query(sql, new Object[]{userId}, new BeanPropertyRowMapper<>(PermissionDto.class)); 44 | List permissions = new ArrayList<>(); 45 | list.forEach(c -> permissions.add(c.getCode())); 46 | return permissions; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /security-spring-boot/src/main/java/com/pbteach/security/springboot/model/PermissionDto.java: -------------------------------------------------------------------------------- 1 | package com.pbteach.security.springboot.model; 2 | 3 | import lombok.Data; 4 | 5 | /** 6 | * @author Administrator 7 | * @version 1.0 8 | **/ 9 | @Data 10 | public class PermissionDto { 11 | 12 | private String id; 13 | private String code; 14 | private String description; 15 | private String url; 16 | } 17 | -------------------------------------------------------------------------------- /security-spring-boot/src/main/java/com/pbteach/security/springboot/model/UserDto.java: -------------------------------------------------------------------------------- 1 | package com.pbteach.security.springboot.model; 2 | 3 | import lombok.Data; 4 | 5 | /** 6 | * @author Administrator 7 | * @version 1.0 8 | **/ 9 | @Data 10 | public class UserDto { 11 | private String id; 12 | private String username; 13 | private String password; 14 | private String fullname; 15 | private String mobile; 16 | } 17 | -------------------------------------------------------------------------------- /security-spring-boot/src/main/java/com/pbteach/security/springboot/service/SpringDataUserDetailsService.java: -------------------------------------------------------------------------------- 1 | package com.pbteach.security.springboot.service; 2 | 3 | import com.pbteach.security.springboot.dao.UserDao; 4 | import com.pbteach.security.springboot.model.UserDto; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.security.core.userdetails.User; 7 | import org.springframework.security.core.userdetails.UserDetails; 8 | import org.springframework.security.core.userdetails.UserDetailsService; 9 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 10 | import org.springframework.stereotype.Service; 11 | 12 | import java.util.List; 13 | 14 | /** 15 | * @author Administrator 16 | * @version 1.0 17 | **/ 18 | @Service 19 | public class SpringDataUserDetailsService implements UserDetailsService { 20 | 21 | @Autowired 22 | UserDao userDao; 23 | 24 | //根据 账号查询用户信息 25 | @Override 26 | public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { 27 | 28 | //将来连接数据库根据账号查询用户信息 29 | UserDto userDto = userDao.getUserByUsername(username); 30 | if(userDto == null){ 31 | //如果用户查不到,返回null,由provider来抛出异常 32 | return null; 33 | } 34 | //根据用户的id查询用户的权限 35 | List permissions = userDao.findPermissionsByUserId(userDto.getId()); 36 | //将permissions转成数组 37 | String[] permissionArray = new String[permissions.size()]; 38 | permissions.toArray(permissionArray); 39 | UserDetails userDetails = User.withUsername(userDto.getUsername()).password(userDto.getPassword()).authorities(permissionArray).build(); 40 | return userDetails; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /security-spring-boot/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | server.port=8080 2 | server.servlet.context-path=/security-springboot 3 | spring.application.name = security-springboot 4 | 5 | spring.mvc.view.prefix=/WEB-INF/view/ 6 | spring.mvc.view.suffix=.jsp 7 | 8 | spring.datasource.url=jdbc:mysql://localhost:3306/user_db 9 | spring.datasource.username=root 10 | spring.datasource.password=mysql 11 | spring.datasource.driver-class-name=com.mysql.jdbc.Driver 12 | 13 | -------------------------------------------------------------------------------- /security-spring-boot/src/main/webapp/WEB-INF/view/login.jsp: -------------------------------------------------------------------------------- 1 | <%@ page contentType="text/html;charset=UTF-8" pageEncoding="utf-8" %> 2 | 3 | 4 | 用户登录 5 | 6 | 7 |
8 | 用户名:
9 | 密   码: 10 |
11 | 12 |
13 | 14 | -------------------------------------------------------------------------------- /security-spring-boot/src/test/java/com/pbteach/security/springboot/TestBCrypt.java: -------------------------------------------------------------------------------- 1 | package com.pbteach.security.springboot; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.security.crypto.bcrypt.BCrypt; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | /** 9 | * @author Administrator 10 | * @version 1.0 11 | **/ 12 | @RunWith(SpringRunner.class) 13 | public class TestBCrypt { 14 | 15 | @Test 16 | public void testBCrypt(){ 17 | 18 | //对密码进行加密 19 | String hashpw = BCrypt.hashpw("secret", BCrypt.gensalt()); 20 | System.out.println(hashpw); 21 | 22 | //校验密码 23 | boolean checkpw = BCrypt.checkpw("123", "$2a$10$aFsOFzujtPCnUCUKcozsHux0rQ/3faAHGFSVb9Y.B1ntpmEhjRtru"); 24 | boolean checkpw2 = BCrypt.checkpw("123", "$2a$10$HuClcUqr/FSLmzSsp9SHqe7D51Keu1sAL7tUAAcb..FyILiLdFKYy"); 25 | System.out.println(checkpw); 26 | System.out.println(checkpw2); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /security-spring-security/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.pbteach.security 8 | security-spring-security 9 | 1.0-SNAPSHOT 10 | war 11 | 12 | UTF-8 13 | 1.8 14 | 1.8 15 | 16 | 17 | 18 | org.springframework.security 19 | spring-security-web 20 | 5.1.4.RELEASE 21 | 22 | 23 | 24 | org.springframework.security 25 | spring-security-config 26 | 5.1.4.RELEASE 27 | 28 | 29 | org.springframework 30 | spring-webmvc 31 | 5.1.5.RELEASE 32 | 33 | 34 | 35 | javax.servlet 36 | javax.servlet-api 37 | 3.0.1 38 | provided 39 | 40 | 41 | org.projectlombok 42 | lombok 43 | 1.18.8 44 | 45 | 46 | 47 | security-springmvc 48 | 49 | 50 | 51 | org.apache.tomcat.maven 52 | tomcat7-maven-plugin 53 | 2.2 54 | 55 | 56 | org.apache.maven.plugins 57 | maven-compiler-plugin 58 | 59 | 1.8 60 | 1.8 61 | 62 | 63 | 64 | 65 | maven-resources-plugin 66 | 67 | utf-8 68 | true 69 | 70 | 71 | src/main/resources 72 | true 73 | 74 | **/* 75 | 76 | 77 | 78 | src/main/java 79 | 80 | **/*.xml 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | -------------------------------------------------------------------------------- /security-spring-security/src/main/java/com/pbteach/security/springmvc/config/ApplicationConfig.java: -------------------------------------------------------------------------------- 1 | package com.pbteach.security.springmvc.config; 2 | 3 | import org.springframework.context.annotation.ComponentScan; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.context.annotation.FilterType; 6 | import org.springframework.stereotype.Controller; 7 | 8 | /** 9 | * @author Administrator 10 | * @version 1.0 11 | **/ 12 | @Configuration //相当于applicationContext.xml 13 | @ComponentScan(basePackages = "com.pbteach.security.springmvc" 14 | ,excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,value = Controller.class)}) 15 | public class ApplicationConfig { 16 | //在此配置除了Controller的其它bean,比如:数据库链接池、事务管理器、业务bean等。 17 | } 18 | -------------------------------------------------------------------------------- /security-spring-security/src/main/java/com/pbteach/security/springmvc/config/WebConfig.java: -------------------------------------------------------------------------------- 1 | package com.pbteach.security.springmvc.config; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.ComponentScan; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.context.annotation.FilterType; 7 | import org.springframework.stereotype.Controller; 8 | import org.springframework.web.servlet.config.annotation.EnableWebMvc; 9 | import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; 10 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 11 | import org.springframework.web.servlet.view.InternalResourceViewResolver; 12 | 13 | /** 14 | * @author Administrator 15 | * @version 1.0 16 | **/ 17 | @Configuration//就相当于springmvc.xml文件 18 | @EnableWebMvc 19 | @ComponentScan(basePackages = "com.pbteach.security.springmvc" 20 | ,includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,value = Controller.class)}) 21 | public class WebConfig implements WebMvcConfigurer { 22 | 23 | 24 | //视频解析器 25 | @Bean 26 | public InternalResourceViewResolver viewResolver(){ 27 | InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); 28 | viewResolver.setPrefix("/WEB-INF/view/"); 29 | viewResolver.setSuffix(".jsp"); 30 | return viewResolver; 31 | } 32 | 33 | @Override 34 | public void addViewControllers(ViewControllerRegistry registry) { 35 | registry.addViewController("/").setViewName("redirect:/login"); 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /security-spring-security/src/main/java/com/pbteach/security/springmvc/config/WebSecurityConfig.java: -------------------------------------------------------------------------------- 1 | package com.pbteach.security.springmvc.config; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 5 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 6 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 7 | import org.springframework.security.core.userdetails.User; 8 | import org.springframework.security.core.userdetails.UserDetailsService; 9 | import org.springframework.security.crypto.password.NoOpPasswordEncoder; 10 | import org.springframework.security.crypto.password.PasswordEncoder; 11 | import org.springframework.security.provisioning.InMemoryUserDetailsManager; 12 | 13 | /** 14 | * @author Administrator 15 | * @version 1.0 16 | **/ 17 | @EnableWebSecurity 18 | public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 19 | 20 | //定义用户信息服务(查询用户信息) 21 | @Bean 22 | public UserDetailsService userDetailsService(){ 23 | InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager(); 24 | manager.createUser(User.withUsername("zhangsan").password("123").authorities("p1").build()); 25 | manager.createUser(User.withUsername("lisi").password("456").authorities("p2").build()); 26 | return manager; 27 | } 28 | 29 | //密码编码器 30 | @Bean 31 | public PasswordEncoder passwordEncoder(){ 32 | return NoOpPasswordEncoder.getInstance(); 33 | } 34 | 35 | //安全拦截机制(最重要) 36 | @Override 37 | protected void configure(HttpSecurity http) throws Exception { 38 | http.authorizeRequests() 39 | .antMatchers("/r/r1").hasAuthority("p1") 40 | .antMatchers("/r/r2").hasAuthority("p2") 41 | .antMatchers("/r/**").authenticated()//所有/r/**的请求必须认证通过 42 | .anyRequest().permitAll()//除了/r/**,其它的请求可以访问 43 | .and() 44 | .formLogin()//允许表单登录 45 | .successForwardUrl("/login-success");//自定义登录成功的页面地址 46 | 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /security-spring-security/src/main/java/com/pbteach/security/springmvc/controller/LoginController.java: -------------------------------------------------------------------------------- 1 | package com.pbteach.security.springmvc.controller; 2 | 3 | import org.springframework.web.bind.annotation.GetMapping; 4 | import org.springframework.web.bind.annotation.RequestMapping; 5 | import org.springframework.web.bind.annotation.RestController; 6 | 7 | /** 8 | * @author Administrator 9 | * @version 1.0 10 | **/ 11 | @RestController 12 | public class LoginController { 13 | 14 | @RequestMapping(value = "/login-success",produces = {"text/plain;charset=UTF-8"}) 15 | public String loginSuccess(){ 16 | return " 登录成功"; 17 | } 18 | 19 | /** 20 | * 测试资源1 21 | * @return 22 | */ 23 | @GetMapping(value = "/r/r1",produces = {"text/plain;charset=UTF-8"}) 24 | public String r1(){ 25 | return " 访问资源1"; 26 | } 27 | 28 | /** 29 | * 测试资源2 30 | * @return 31 | */ 32 | @GetMapping(value = "/r/r2",produces = {"text/plain;charset=UTF-8"}) 33 | public String r2(){ 34 | return " 访问资源2"; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /security-spring-security/src/main/java/com/pbteach/security/springmvc/init/SpringApplicationInitializer.java: -------------------------------------------------------------------------------- 1 | package com.pbteach.security.springmvc.init; 2 | 3 | import com.pbteach.security.springmvc.config.ApplicationConfig; 4 | import com.pbteach.security.springmvc.config.WebConfig; 5 | import com.pbteach.security.springmvc.config.WebSecurityConfig; 6 | import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; 7 | 8 | /** 9 | * @author Administrator 10 | * @version 1.0 11 | **/ 12 | public class SpringApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { 13 | 14 | //spring容器,相当于加载 applicationContext.xml 15 | @Override 16 | protected Class[] getRootConfigClasses() { 17 | return new Class[]{ApplicationConfig.class, WebSecurityConfig.class}; 18 | } 19 | 20 | //servletContext,相当于加载springmvc.xml 21 | @Override 22 | protected Class[] getServletConfigClasses() { 23 | return new Class[]{WebConfig.class}; 24 | } 25 | 26 | //url-mapping 27 | @Override 28 | protected String[] getServletMappings() { 29 | return new String[]{"/"}; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /security-spring-security/src/main/java/com/pbteach/security/springmvc/init/SpringSecurityApplicationInitializer.java: -------------------------------------------------------------------------------- 1 | package com.pbteach.security.springmvc.init; 2 | 3 | import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer; 4 | 5 | /** 6 | * @author Administrator 7 | * @version 1.0 8 | **/ 9 | public class SpringSecurityApplicationInitializer 10 | extends AbstractSecurityWebApplicationInitializer { 11 | public SpringSecurityApplicationInitializer() { 12 | //super(WebSecurityConfig.class); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /security-springmvc/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.pbteach.security 8 | security-springmvc 9 | 1.0-SNAPSHOT 10 | war 11 | 12 | UTF-8 13 | 1.8 14 | 1.8 15 | 16 | 17 | 18 | org.springframework 19 | spring-webmvc 20 | 5.1.5.RELEASE 21 | 22 | 23 | 24 | javax.servlet 25 | javax.servlet-api 26 | 3.0.1 27 | provided 28 | 29 | 30 | org.projectlombok 31 | lombok 32 | 1.18.8 33 | 34 | 35 | 36 | security-springmvc 37 | 38 | 39 | 40 | org.apache.tomcat.maven 41 | tomcat7-maven-plugin 42 | 2.2 43 | 44 | 45 | org.apache.maven.plugins 46 | maven-compiler-plugin 47 | 48 | 1.8 49 | 1.8 50 | 51 | 52 | 53 | 54 | maven-resources-plugin 55 | 56 | utf-8 57 | true 58 | 59 | 60 | src/main/resources 61 | true 62 | 63 | **/* 64 | 65 | 66 | 67 | src/main/java 68 | 69 | **/*.xml 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | -------------------------------------------------------------------------------- /security-springmvc/src/main/java/com/pbteach/security/springmvc/config/ApplicationConfig.java: -------------------------------------------------------------------------------- 1 | package com.pbteach.security.springmvc.config; 2 | 3 | import org.springframework.context.annotation.ComponentScan; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.context.annotation.FilterType; 6 | import org.springframework.stereotype.Controller; 7 | 8 | /** 9 | * @author Administrator 10 | * @version 1.0 11 | **/ 12 | @Configuration //相当于applicationContext.xml 13 | @ComponentScan(basePackages = "com.pbteach.security.springmvc" 14 | ,excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,value = Controller.class)}) 15 | public class ApplicationConfig { 16 | //在此配置除了Controller的其它bean,比如:数据库链接池、事务管理器、业务bean等。 17 | } 18 | -------------------------------------------------------------------------------- /security-springmvc/src/main/java/com/pbteach/security/springmvc/config/WebConfig.java: -------------------------------------------------------------------------------- 1 | package com.pbteach.security.springmvc.config; 2 | 3 | import com.pbteach.security.springmvc.interceptor.SimpleAuthenticationInterceptor; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.context.annotation.ComponentScan; 7 | import org.springframework.context.annotation.Configuration; 8 | import org.springframework.context.annotation.FilterType; 9 | import org.springframework.stereotype.Controller; 10 | import org.springframework.web.servlet.config.annotation.EnableWebMvc; 11 | import org.springframework.web.servlet.config.annotation.InterceptorRegistry; 12 | import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; 13 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 14 | import org.springframework.web.servlet.view.InternalResourceViewResolver; 15 | 16 | /** 17 | * @author Administrator 18 | * @version 1.0 19 | **/ 20 | @Configuration//就相当于springmvc.xml文件 21 | @EnableWebMvc 22 | @ComponentScan(basePackages = "com.pbteach.security.springmvc" 23 | ,includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,value = Controller.class)}) 24 | public class WebConfig implements WebMvcConfigurer { 25 | 26 | @Autowired 27 | SimpleAuthenticationInterceptor simpleAuthenticationInterceptor; 28 | 29 | //视频解析器 30 | @Bean 31 | public InternalResourceViewResolver viewResolver(){ 32 | InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); 33 | viewResolver.setPrefix("/WEB-INF/view/"); 34 | viewResolver.setSuffix(".jsp"); 35 | return viewResolver; 36 | } 37 | 38 | @Override 39 | public void addViewControllers(ViewControllerRegistry registry) { 40 | registry.addViewController("/").setViewName("login"); 41 | } 42 | 43 | @Override 44 | public void addInterceptors(InterceptorRegistry registry) { 45 | registry.addInterceptor(simpleAuthenticationInterceptor).addPathPatterns("/r/**"); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /security-springmvc/src/main/java/com/pbteach/security/springmvc/controller/LoginController.java: -------------------------------------------------------------------------------- 1 | package com.pbteach.security.springmvc.controller; 2 | 3 | import com.pbteach.security.springmvc.model.AuthenticationRequest; 4 | import com.pbteach.security.springmvc.model.UserDto; 5 | import com.pbteach.security.springmvc.service.AuthenticationService; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.web.bind.annotation.GetMapping; 8 | import org.springframework.web.bind.annotation.RequestMapping; 9 | import org.springframework.web.bind.annotation.RestController; 10 | 11 | import javax.servlet.http.HttpSession; 12 | 13 | /** 14 | * @author Administrator 15 | * @version 1.0 16 | **/ 17 | @RestController 18 | public class LoginController { 19 | 20 | @Autowired 21 | AuthenticationService authenticationService; 22 | 23 | @RequestMapping(value = "/login",produces = "text/plain;charset=utf-8") 24 | public String login(AuthenticationRequest authenticationRequest, HttpSession session){ 25 | UserDto userDto = authenticationService.authentication(authenticationRequest); 26 | //存入session 27 | session.setAttribute(UserDto.SESSION_USER_KEY,userDto); 28 | return userDto.getUsername() +"登录成功"; 29 | } 30 | 31 | @GetMapping(value = "/logout",produces = {"text/plain;charset=UTF-8"}) 32 | public String logout(HttpSession session){ 33 | session.invalidate(); 34 | return "退出成功"; 35 | } 36 | 37 | @GetMapping(value = "/r/r1",produces = {"text/plain;charset=UTF-8"}) 38 | public String r1(HttpSession session){ 39 | String fullname = null; 40 | Object object = session.getAttribute(UserDto.SESSION_USER_KEY); 41 | if(object == null){ 42 | fullname = "匿名"; 43 | }else{ 44 | UserDto userDto = (UserDto) object; 45 | fullname = userDto.getFullname(); 46 | } 47 | return fullname+"访问资源r1"; 48 | } 49 | @GetMapping(value = "/r/r2",produces = {"text/plain;charset=UTF-8"}) 50 | public String r2(HttpSession session){ 51 | String fullname = null; 52 | Object userObj = session.getAttribute(UserDto.SESSION_USER_KEY); 53 | if(userObj != null){ 54 | fullname = ((UserDto)userObj).getFullname(); 55 | }else{ 56 | fullname = "匿名"; 57 | } 58 | return fullname + " 访问资源2"; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /security-springmvc/src/main/java/com/pbteach/security/springmvc/init/SpringApplicationInitializer.java: -------------------------------------------------------------------------------- 1 | package com.pbteach.security.springmvc.init; 2 | 3 | import com.pbteach.security.springmvc.config.ApplicationConfig; 4 | import com.pbteach.security.springmvc.config.WebConfig; 5 | import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; 6 | 7 | /** 8 | * @author Administrator 9 | * @version 1.0 10 | **/ 11 | public class SpringApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { 12 | 13 | //spring容器,相当于加载 applicationContext.xml 14 | @Override 15 | protected Class[] getRootConfigClasses() { 16 | return new Class[]{ApplicationConfig.class}; 17 | } 18 | 19 | //servletContext,相当于加载springmvc.xml 20 | @Override 21 | protected Class[] getServletConfigClasses() { 22 | return new Class[]{WebConfig.class}; 23 | } 24 | 25 | //url-mapping 26 | @Override 27 | protected String[] getServletMappings() { 28 | return new String[]{"/"}; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /security-springmvc/src/main/java/com/pbteach/security/springmvc/interceptor/SimpleAuthenticationInterceptor.java: -------------------------------------------------------------------------------- 1 | package com.pbteach.security.springmvc.interceptor; 2 | 3 | import com.pbteach.security.springmvc.model.UserDto; 4 | import org.springframework.stereotype.Component; 5 | import org.springframework.web.servlet.HandlerInterceptor; 6 | 7 | import javax.servlet.http.HttpServletRequest; 8 | import javax.servlet.http.HttpServletResponse; 9 | import java.io.IOException; 10 | import java.io.PrintWriter; 11 | 12 | /** 13 | * @author Administrator 14 | * @version 1.0 15 | **/ 16 | @Component 17 | public class SimpleAuthenticationInterceptor implements HandlerInterceptor { 18 | 19 | @Override 20 | public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { 21 | //在这个方法中校验用户请求的url是否在用户的权限范围内 22 | //取出用户身份信息 23 | Object object = request.getSession().getAttribute(UserDto.SESSION_USER_KEY); 24 | if(object == null){ 25 | //没有认证,提示登录 26 | writeContent(response,"请登录"); 27 | } 28 | UserDto userDto = (UserDto) object; 29 | //请求的url 30 | String requestURI = request.getRequestURI(); 31 | if( userDto.getAuthorities().contains("p1") && requestURI.contains("/r/r1")){ 32 | return true; 33 | } 34 | if( userDto.getAuthorities().contains("p2") && requestURI.contains("/r/r2")){ 35 | return true; 36 | } 37 | writeContent(response,"没有权限,拒绝访问"); 38 | 39 | return false; 40 | } 41 | 42 | //响应信息给客户端 43 | private void writeContent(HttpServletResponse response, String msg) throws IOException { 44 | response.setContentType("text/html;charset=utf-8"); 45 | PrintWriter writer = response.getWriter(); 46 | writer.print(msg); 47 | writer.close(); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /security-springmvc/src/main/java/com/pbteach/security/springmvc/model/AuthenticationRequest.java: -------------------------------------------------------------------------------- 1 | package com.pbteach.security.springmvc.model; 2 | 3 | import lombok.Data; 4 | 5 | /** 6 | * @author Administrator 7 | * @version 1.0 8 | **/ 9 | @Data 10 | public class AuthenticationRequest { 11 | //认证请求参数,账号、密码。。 12 | /** 13 | * 用户名 14 | */ 15 | private String username; 16 | 17 | /** 18 | * 密码 19 | */ 20 | private String password; 21 | 22 | } 23 | -------------------------------------------------------------------------------- /security-springmvc/src/main/java/com/pbteach/security/springmvc/model/UserDto.java: -------------------------------------------------------------------------------- 1 | package com.pbteach.security.springmvc.model; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Data; 5 | 6 | import java.util.Set; 7 | 8 | /** 9 | * @author Administrator 10 | * @version 1.0 11 | **/ 12 | @Data 13 | @AllArgsConstructor 14 | public class UserDto { 15 | public static final String SESSION_USER_KEY = "_user"; 16 | //用户身份信息 17 | private String id; 18 | private String username; 19 | private String password; 20 | private String fullname; 21 | private String mobile; 22 | /** 23 | * 用户权限 24 | */ 25 | private Set authorities; 26 | } 27 | -------------------------------------------------------------------------------- /security-springmvc/src/main/java/com/pbteach/security/springmvc/service/AuthenticationService.java: -------------------------------------------------------------------------------- 1 | package com.pbteach.security.springmvc.service; 2 | 3 | import com.pbteach.security.springmvc.model.AuthenticationRequest; 4 | import com.pbteach.security.springmvc.model.UserDto; 5 | 6 | /** 7 | * Created by Administrator. 8 | */ 9 | public interface AuthenticationService { 10 | /** 11 | * 用户认证 12 | * @param authenticationRequest 用户认证请求,账号和密码 13 | * @return 认证成功的用户信息 14 | */ 15 | UserDto authentication(AuthenticationRequest authenticationRequest); 16 | } 17 | -------------------------------------------------------------------------------- /security-springmvc/src/main/java/com/pbteach/security/springmvc/service/AuthenticationServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.pbteach.security.springmvc.service; 2 | 3 | import com.pbteach.security.springmvc.model.AuthenticationRequest; 4 | import com.pbteach.security.springmvc.model.UserDto; 5 | import org.springframework.stereotype.Service; 6 | import org.springframework.util.StringUtils; 7 | 8 | import java.util.HashMap; 9 | import java.util.HashSet; 10 | import java.util.Map; 11 | import java.util.Set; 12 | 13 | /** 14 | * @author Administrator 15 | * @version 1.0 16 | **/ 17 | @Service 18 | public class AuthenticationServiceImpl implements AuthenticationService{ 19 | /** 20 | * 用户认证,校验用户身份信息是否合法 21 | * 22 | * @param authenticationRequest 用户认证请求,账号和密码 23 | * @return 认证成功的用户信息 24 | */ 25 | @Override 26 | public UserDto authentication(AuthenticationRequest authenticationRequest) { 27 | //校验参数是否为空 28 | if(authenticationRequest == null 29 | || StringUtils.isEmpty(authenticationRequest.getUsername()) 30 | || StringUtils.isEmpty(authenticationRequest.getPassword())){ 31 | throw new RuntimeException("账号和密码为空"); 32 | } 33 | //根据账号去查询数据库,这里测试程序采用模拟方法 34 | UserDto user = getUserDto(authenticationRequest.getUsername()); 35 | //判断用户是否为空 36 | if(user == null){ 37 | throw new RuntimeException("查询不到该用户"); 38 | } 39 | //校验密码 40 | if(!authenticationRequest.getPassword().equals(user.getPassword())){ 41 | throw new RuntimeException("账号或密码错误"); 42 | } 43 | //认证通过,返回用户身份信息 44 | return user; 45 | } 46 | //根据账号查询用户信息 47 | private UserDto getUserDto(String userName){ 48 | return userMap.get(userName); 49 | } 50 | //用户信息 51 | private Map userMap = new HashMap<>(); 52 | { 53 | Set authorities1 = new HashSet<>(); 54 | authorities1.add("p1");//这个p1我们人为让它和/r/r1对应 55 | Set authorities2 = new HashSet<>(); 56 | authorities2.add("p2");//这个p2我们人为让它和/r/r2对应 57 | userMap.put("zhangsan",new UserDto("1010","zhangsan","123","张三","133443",authorities1)); 58 | userMap.put("lisi",new UserDto("1011","lisi","456","李四","144553",authorities2)); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /security-springmvc/src/main/webapp/WEB-INF/view/login.jsp: -------------------------------------------------------------------------------- 1 | <%@ page contentType="text/html;charset=UTF-8" pageEncoding="utf-8" %> 2 | 3 | 4 | 用户登录 5 | 6 | 7 |
8 | 用户名:
9 | 密   码: 10 |
11 | 12 |
13 | 14 | --------------------------------------------------------------------------------