pom.xml
@@ -11,6 +11,7 @@ <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <!--<version>1.5.20.RELEASE</version>--> <version>2.1.12.RELEASE</version> <!--<version>2.2.0.RELEASE</version>--> <relativePath/> @@ -20,6 +21,10 @@ <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> @@ -47,6 +52,10 @@ <artifactId>shiro-spring-boot-web-starter</artifactId> <version>1.5.3</version> </dependency> <!--<dependency>--> <!-- <groupId>org.springframework.boot</groupId>--> <!-- <artifactId>spring-boot-starter-thymeleaf</artifactId>--> <!--</dependency>--> <!--mybatis 及mybatis-plus--> <dependency> <groupId>com.baomidou</groupId> src/main/java/com/whyc/Application.java
@@ -3,10 +3,14 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ServletComponentScan; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.InternalResourceViewResolver; /** * @Description : 启动类 @@ -14,19 +18,12 @@ **/ @SpringBootApplication @EnableWebMvc @ServletComponentScan(basePackages = "com.whyc.filter") @ServletComponentScan(basePackages = {"com.whyc.filter","com.whyc.servlet"}) @EnableCaching public class Application extends WebMvcConfigurerAdapter implements WebMvcConfigurer { public static void main(String[] args) { SpringApplication.run(Application.class,args); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { //super.addResourceHandlers(registry); //registry.addResourceHandler("/**").addResourceLocations("/"); registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); } } src/main/java/com/whyc/config/ShiroConfig.java
@@ -1,5 +1,6 @@ package com.whyc.config; import com.whyc.filter.RolesOrAuthorizationFilter; import com.whyc.properties.PropertiesUtil; import com.whyc.realm.CustomRealm; import lombok.extern.log4j.Log4j; @@ -7,6 +8,7 @@ import org.apache.shiro.spring.LifecycleBeanPostProcessor; import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.web.filter.authz.RolesAuthorizationFilter; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator; import org.springframework.beans.factory.annotation.Autowired; @@ -14,6 +16,8 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.DependsOn; import javax.servlet.Filter; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -22,7 +26,7 @@ * 暂时提供权限管理,会话管理后续更新 TODO */ @Configuration @Log4j2 //@Log4j2 public class ShiroConfig { @Autowired @@ -68,22 +72,30 @@ for (Object object : list) { String key = object.toString(); String value = PropertiesUtil.getShiroValue(key); log.info("读取防止盗链控制:---key{},---value:{}",key,value); //log.info("读取防止盗链控制:---key{},---value:{}",key,value); map.put(key, value); } return map; } /**自定义过滤器*/ private Map<String, Filter> filters(){ HashMap<String, Filter> map = new HashMap<>(); map.put("rolesOr",new RolesOrAuthorizationFilter()); return map; } /**过滤器*/ // @Bean("shiroFilter") @Bean public ShiroFilterFactoryBean shiroFilterFactoryBean(){ ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean(); //注入新定义的过滤器 shiroFilter.setFilters(filters()); shiroFilter.setSecurityManager(defaultWebSecurityManager()); shiroFilter.setFilterChainDefinitionMap(filterChainDefinition()); //shiroFilter.setLoginUrl("/login"); //shiroFilter.setUnauthorizedUrl("/login"); shiroFilter.setLoginUrl("/login.html"); shiroFilter.setUnauthorizedUrl("/login/unauthorized"); return shiroFilter; } } src/main/java/com/whyc/config/StaticResourceConfig.java
New file @@ -0,0 +1,31 @@ package com.whyc.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.*; /** * @Description : static resources Config * @date 2020/09/15 **/ @Configuration @EnableWebMvc public class StaticResourceConfig extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { //这个是可行的,解析的时候path为*.html,校验路径admin下是否存在 //registry.addResourceHandler("admin/*.html").addResourceLocations("classpath:/META-INF/resources/admin/"); registry.addResourceHandler("/login.html").addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("*.html").addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); registry.addResourceHandler("/service-worker.js").addResourceLocations("classpath:/META-INF/resources/"); super.addResourceHandlers(registry); //registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/"); //registry.addResourceHandler("*.html").addResourceLocations("classpath:/META-INF/resources/"); //registry.addResourceHandler("/admin/").addResourceLocations("classpath:/META-INF/resources/admin/"); //registry.addResourceHandler("/favicon.ico"); } } src/main/java/com/whyc/controller/LoginController.java
@@ -6,6 +6,8 @@ import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import springfox.documentation.annotations.ApiIgnore; import javax.servlet.ServletException; @@ -33,10 +35,24 @@ service.logout(); } /**拦截登录*/ @GetMapping("login") /**拦截登录*//* @GetMapping("/") @ApiIgnore public void login(){ System.out.printf("请登录..."); public ModelAndView toLoginHtml(HttpServletRequest request, HttpServletResponse response,ModelAndView view) throws ServletException, IOException { //request.getRequestDispatcher("login.html").forward(request,response); System.out.println("转发啦..."); //response.setContentType("text/html;charset=utf-8"); //response.sendRedirect("http://localhost:8090/login.html"); //response.sendRedirect("/login.html"); view.setViewName("login"); return view; }*/ /**拦截登录*/ @GetMapping("unauthorized") @ApiIgnore public void unauthorized(HttpServletRequest request,HttpServletResponse response) throws IOException { response.setContentType("text/html;charset=utf-8"); response.getWriter().write("您未获取到接口的调用授权,拒绝访问!"); } } src/main/java/com/whyc/controller/WaterCommController.java
@@ -6,6 +6,7 @@ import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; src/main/java/com/whyc/filter/CrossDomainFilter.java
@@ -1,6 +1,7 @@ package com.whyc.filter; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @@ -9,6 +10,7 @@ * @Description : * @date 2020/09/11 **/ @WebFilter public class CrossDomainFilter implements Filter { src/main/java/com/whyc/filter/LoginFilter.java
@@ -1,58 +1,58 @@ package com.whyc.filter; import com.whyc.pojo.User; import lombok.extern.slf4j.Slf4j; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.annotation.WebInitParam; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.io.PrintWriter; @Slf4j /*@WebFilter(filterName = "loginFilter",urlPatterns = "/*",initParams = { @WebInitParam(name = "exclusions",value = "*.css,*.js") })*/ //@WebInitParam(name = "exclusions",value = "*.css,*.js") public class LoginFilter implements Filter { private String exclusions = ""; public void destroy() { } public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { HttpServletRequest request=(HttpServletRequest)req; String URL=request.getRequestURI(); String[] uri=request.getRequestURI().split("/"); String source=""; if(uri.length>0) { source = uri[uri.length - 1]; } String suffix = source.substring(source.indexOf(".")+1); User user=(User)request.getSession().getAttribute("user"); //不拦截swagger的资源请求,以及登录请求 if(URL.indexOf("swagger-resources")>-1 ||URL.indexOf("swagger-ui")>-1 ||URL.indexOf("v2/api-docs")>-1||URL.indexOf("login")>-1){ chain.doFilter(req,resp); } //不拦截静态资源css/js else if(exclusions.indexOf(suffix)>-1){ chain.doFilter(req,resp); } else if(user!=null){ chain.doFilter(req, resp); }else{ PrintWriter out=resp.getWriter(); out.print("<script charset='UTF-8'>window.location.href='index.html'</script>"); } } public void init(FilterConfig config) throws ServletException { exclusions =config.getInitParameter("exclusions"); } } //package com.whyc.filter; // //import com.whyc.pojo.User; //import lombok.extern.slf4j.Slf4j; // //import javax.servlet.*; //import javax.servlet.annotation.WebFilter; //import javax.servlet.annotation.WebInitParam; //import javax.servlet.http.HttpServletRequest; //import java.io.IOException; //import java.io.PrintWriter; // //@Slf4j ///*@WebFilter(filterName = "loginFilter",urlPatterns = "/*",initParams = { // @WebInitParam(name = "exclusions",value = "*.css,*.js") //})*/ ////@WebInitParam(name = "exclusions",value = "*.css,*.js") //public class LoginFilter implements Filter { // // private String exclusions = ""; // // public void destroy() { // } // // public void doFilter(ServletRequest req, ServletResponse resp, // FilterChain chain) throws IOException, ServletException { // HttpServletRequest request=(HttpServletRequest)req; // // String URL=request.getRequestURI(); // String[] uri=request.getRequestURI().split("/"); // String source=""; // if(uri.length>0) { // source = uri[uri.length - 1]; // } // String suffix = source.substring(source.indexOf(".")+1); // User user=(User)request.getSession().getAttribute("user"); // // //不拦截swagger的资源请求,以及登录请求 // if(URL.indexOf("swagger-resources")>-1 ||URL.indexOf("swagger-ui")>-1 ||URL.indexOf("v2/api-docs")>-1||URL.indexOf("login")>-1){ // chain.doFilter(req,resp); // } // //不拦截静态资源css/js // else if(exclusions.indexOf(suffix)>-1){ // chain.doFilter(req,resp); // } // else if(user!=null){ // chain.doFilter(req, resp); // }else{ // PrintWriter out=resp.getWriter(); // out.print("<script charset='UTF-8'>window.location.href='index.html'</script>"); // } // } // // public void init(FilterConfig config) throws ServletException { // exclusions =config.getInitParameter("exclusions"); // } // //} src/main/java/com/whyc/filter/RolesOrAuthorizationFilter.java
New file @@ -0,0 +1,36 @@ package com.whyc.filter; import com.whyc.pojo.User; import org.apache.shiro.subject.Subject; import org.apache.shiro.util.CollectionUtils; import org.apache.shiro.web.filter.authz.AuthorizationFilter; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import java.util.Set; /** * 自定义过滤规则,只需要包含某个角色,就授权 */ public class RolesOrAuthorizationFilter extends AuthorizationFilter { @Override protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception { Subject subject = getSubject(request, response); String[] rolesArray = (String[]) mappedValue; if (rolesArray == null || rolesArray.length == 0) { return true; } Set<String> roles = CollectionUtils.asSet(rolesArray); //判断为or User user = (User) subject.getPrincipals().getPrimaryPrincipal(); for (String role :roles){ if (subject.hasRole(role)){ return true; } } return false; } } src/main/java/com/whyc/mapper/SecurityMapper.java
File was deleted src/main/java/com/whyc/service/UserBridgeService.java
@@ -1,17 +1,15 @@ package com.whyc.service; import com.baomidou.mybatisplus.core.conditions.Wrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.whyc.mapper.PermissionMapper; import com.whyc.mapper.RoleMapper; import com.whyc.mapper.SecurityMapper; import com.whyc.mapper.UserMapper; import com.whyc.pojo.Permission; import com.whyc.pojo.Role; import com.whyc.pojo.User; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import javax.annotation.Resource; @@ -44,6 +42,7 @@ } } @Cacheable(cacheNames = "authorizationCache",key = "#root.method") public AuthorizationInfo getAuthorizationInfo(User user) { SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); //添加Roles和Permissions @@ -57,12 +56,14 @@ private List<String> findPermissionsByUserId(int userId) { QueryWrapper<Permission> query = Wrappers.query(); List<String> perms = null; List<String> perms = new LinkedList<>(); //perms.add("water:all"); return perms; } private List<String> findRolesByUserId(int userId) { List<String> roles = null; List<String> roles = new LinkedList<>(); //roles.add("dev"); return roles; } } src/main/java/com/whyc/swagger/webAppConfig.java
File was deleted src/main/resources/config/application.yml
@@ -1,6 +1,8 @@ #服务端口号 server: port: 8090 # servlet: # context-path: /motor #数据库 spring: @@ -18,11 +20,6 @@ initialPoolSize: 2 minPoolSize: 2 maxPoolSize: 500 mvc: view: prefix: /WEB-INF/views suffix: .html mybatis-plus: typeAliasesPackage: com.whyc.pojo mapper-locations: classpath:mapper/**/*Mapper.xml src/main/resources/config/authentication.properties
@@ -1,17 +1,27 @@ #dev接口调试时使用 /**=anon #静态资源不拦截 /static/**=anon #登录链接不拦截 /login/**=anon login.html=anon /login/**=anon index.html=anon #接口文档相关不拦截 /doc.html=anon /webjars/**=anon /swagger-resources=anon /swagger-resources/**=anon /v2/api-docs-ext=anon /v2/api-docs=anon #访问/resource/**需要有admin的角色 #/resource/**=roles-or[dev,SuperAdmin] #设置需要permission的拦截 /WaterComm/**=perms["water:all"] #设置RolesOr拦截 #/WaterComm/**=rolesOr["admin","dev"] #其他链接是需要登录的 #/**=authc src/main/webapp/login.html
File was renamed from src/main/webapp/WEB-INF/views/login.html @@ -5,6 +5,6 @@ <title>Title</title> </head> <body> <h1>login页面</h1> <h1>Login页面加载成功!</h1> </body> </html>