当前位置: 首页 > news >正文

东营网站建设优化/360安全浏览器

东营网站建设优化,360安全浏览器,成都十大互联网公司,鲜花网站建设项目概述spring security 的核心功能主要包括:认证授权攻击防护其核心就是一组过滤器链,项目启动后将会自动配置。最核心的就是 Basic Authentication Filter 用来认证用户的身份,一个在spring security中一种过滤器处理一种认证方式。 package com.…
  • spring security 的核心功能主要包括:
  • 认证
  • 授权
  • 攻击防护
  • 其核心就是一组过滤器链,项目启动后将会自动配置。最核心的就是 Basic Authentication Filter
    用来认证用户的身份,一个在spring security中一种过滤器处理一种认证方式。
package com.programb.example;import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;import static org.springframework.boot.SpringApplication.run;@ComponentScan(basePackages ="com.programb.example")
@SpringBootApplication
public class Application {public static void main(String[] args) {ConfigurableApplicationContext run = run(Application.class, args);}}
package com.programb.example.config;import java.beans.PropertyVetoException;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import com.mchange.v2.c3p0.ComboPooledDataSource;@Configuration
public class DBconfig {@Autowiredprivate Environment env;@Bean(name="dataSource")public ComboPooledDataSource dataSource() throws PropertyVetoException {ComboPooledDataSource dataSource = new ComboPooledDataSource();dataSource.setDriverClass(env.getProperty("ms.db.driverClassName"));dataSource.setJdbcUrl(env.getProperty("ms.db.url"));dataSource.setUser(env.getProperty("ms.db.username"));dataSource.setPassword(env.getProperty("ms.db.password"));dataSource.setMaxPoolSize(20);dataSource.setMinPoolSize(5);dataSource.setInitialPoolSize(10);dataSource.setMaxIdleTime(300);dataSource.setAcquireIncrement(5);dataSource.setIdleConnectionTestPeriod(60);return dataSource;}
}
package com.programb.example.config;import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;import javax.sql.DataSource;@Configuration
@ComponentScan
public class MyBatisConfig {@Autowiredprivate DataSource dataSource;@Bean(name = "sqlSessionFactory")public SqlSessionFactoryBean sqlSessionFactory(ApplicationContext applicationContext) throws Exception {SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();sessionFactory.setDataSource(dataSource);// sessionFactory.setPlugins(new Interceptor[]{new PageInterceptor()});sessionFactory.setMapperLocations(applicationContext.getResources("classpath*:mapper/*.xml"));return sessionFactory;}}
package com.programb.example.config;import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
public class MyBatisScannerConfig {@Beanpublic MapperScannerConfigurer MapperScannerConfigurer() {MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();mapperScannerConfigurer.setBasePackage("com.programb.example.dao");mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");return mapperScannerConfigurer;}
}
package com.programb.example.config;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;import javax.sql.DataSource;@Configuration
@ComponentScan
public class TransactionConfig implements TransactionManagementConfigurer{@Autowiredprivate DataSource dataSource;@Bean(name = "transactionManager")@Overridepublic PlatformTransactionManager annotationDrivenTransactionManager() {return new DataSourceTransactionManager(dataSource);}}
package com.programb.example.config;import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;@Configurationpublic class WebMvcConfig extends WebMvcConfigurerAdapter{@Overridepublic void addViewControllers(ViewControllerRegistry registry) {registry.addViewController("/login").setViewName("login");}
}
package com.programb.example.config;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;import com.programb.example.service.CustomUserService;
import com.programb.example.service.MyFilterSecurityInterceptor;@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {@Autowiredprivate MyFilterSecurityInterceptor myFilterSecurityInterceptor;@BeanUserDetailsService customUserService() { //注册UserDetailsService 的beanreturn new CustomUserService();}@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.userDetailsService(customUserService()); //user Details Service验证}@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().anyRequest().authenticated() //任何请求,登录后可以访问.and().formLogin().loginPage("/login").failureUrl("/login?error").permitAll() //登录页面用户任意访问.and().logout().permitAll(); //注销行为任意访问http.addFilterBefore(myFilterSecurityInterceptor, FilterSecurityInterceptor.class).csrf().disable();}
}
package com.programb.example.controller;import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;import com.programb.example.domain.Msg;@Controller
public class HomeController {@RequestMapping("/")public String index(Model model){Msg msg =  new Msg("测试标题","测试内容","欢迎来到HOME页面,您拥有 ROLE_HOME 权限");model.addAttribute("msg", msg);return "home";}@RequestMapping("/admin")@ResponseBodypublic String hello(){return "hello admin";}@RequestMapping("/login")public String login(){return "login";}@RequestMapping(value = "/user", method = RequestMethod.GET)@ResponseBodypublic String getList(){return "hello getList";}@RequestMapping(value = "/user", method = RequestMethod.POST)@ResponseBodypublic String save(){return "hello save";}@RequestMapping(value = "/user", method = RequestMethod.PUT)@ResponseBodypublic String update(){return "hello update";}
}
package com.programb.example.dao;import java.util.List;import com.programb.example.domain.Permission;public interface PermissionDao {public List<Permission> findAll();public List<Permission> findByAdminUserId(int userId);
}
package com.programb.example.dao;import com.programb.example.domain.SysUser;public interface UserDao {public SysUser findByUserName(String username);
}
package com.programb.example.domain;public class Msg {private String title;private String content;private String etraInfo;public Msg(String title, String content, String etraInfo) {super();this.title = title;this.content = content;this.etraInfo = etraInfo;}public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public String getContent() {return content;}public void setContent(String content) {this.content = content;}public String getEtraInfo() {return etraInfo;}public void setEtraInfo(String etraInfo) {this.etraInfo = etraInfo;}}
package com.programb.example.domain;public class Permission {private int id;//权限名称private String name;//权限描述private String descritpion;//授权链接private String url;//父节点idprivate int pid;//请求方法private String method;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getDescritpion() {return descritpion;}public void setDescritpion(String descritpion) {this.descritpion = descritpion;}public String getUrl() {return url;}public void setUrl(String url) {this.url = url;}public int getPid() {return pid;}public void setPid(int pid) {this.pid = pid;}public String getMethod() {return method;}public void setMethod(String method) {this.method = method;}}
package com.programb.example.domain;public class SysRole {private Integer id;private String name;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}}
package com.programb.example.domain;import java.util.List;public class SysUser {private Integer id;private String username;private String password;private List<SysRole> roles;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public List<SysRole> getRoles() {return roles;}public void setRoles(List<SysRole> roles) {this.roles = roles;}}
package com.programb.example.service;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;import com.programb.example.dao.PermissionDao;
import com.programb.example.dao.UserDao;
import com.programb.example.domain.Permission;
import com.programb.example.domain.SysRole;
import com.programb.example.domain.SysUser;import java.util.ArrayList;
import java.util.List;@Service
public class CustomUserService implements UserDetailsService { //自定义UserDetailsService 接口@AutowiredUserDao userDao;@AutowiredPermissionDao permissionDao;public UserDetails loadUserByUsername(String username) {SysUser user = userDao.findByUserName(username);if (user != null) {List<Permission> permissions = permissionDao.findByAdminUserId(user.getId());List<GrantedAuthority> grantedAuthorities = new ArrayList<>();for (Permission permission : permissions) {if (permission != null && permission.getName() != null) {GrantedAuthority grantedAuthority = new MyGrantedAuthority(permission.getUrl(), permission.getMethod());grantedAuthorities.add(grantedAuthority);}}return new User(user.getUsername(), user.getPassword(), grantedAuthorities);} else {throw new UsernameNotFoundException("admin: " + username + " do not exist!");}}}
package com.programb.example.service;import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Service;import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.Iterator;@Service
public class MyAccessDecisionManager implements AccessDecisionManager {//decide 方法是判定是否拥有权限的决策方法@Overridepublic void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {HttpServletRequest request = ((FilterInvocation) object).getHttpRequest();String url, method;AntPathRequestMatcher matcher;for (GrantedAuthority ga : authentication.getAuthorities()) {if (ga instanceof MyGrantedAuthority) {MyGrantedAuthority urlGrantedAuthority = (MyGrantedAuthority) ga;url = urlGrantedAuthority.getPermissionUrl();method = urlGrantedAuthority.getMethod();matcher = new AntPathRequestMatcher(url);if (matcher.matches(request)) {//当权限表权限的method为ALL时表示拥有此路径的所有请求方式权利。if (method.equals(request.getMethod()) || "ALL".equals(method)) {return;}}} else if (ga.getAuthority().equals("ROLE_ANONYMOUS")) {//未登录只允许访问 login 页面matcher = new AntPathRequestMatcher("/login");if (matcher.matches(request)) {return;}}}throw new AccessDeniedException("no right");}@Overridepublic boolean supports(ConfigAttribute attribute) {return true;}@Overridepublic boolean supports(Class<?> clazz) {return true;}
}
package com.programb.example.service;import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.SecurityMetadataSource;
import org.springframework.security.access.intercept.AbstractSecurityInterceptor;
import org.springframework.security.access.intercept.InterceptorStatusToken;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Service;import java.io.IOException;@Service
public class MyFilterSecurityInterceptor extends AbstractSecurityInterceptor implements Filter {@Autowiredprivate FilterInvocationSecurityMetadataSource securityMetadataSource;@Autowiredpublic void setMyAccessDecisionManager(MyAccessDecisionManager myAccessDecisionManager) {super.setAccessDecisionManager(myAccessDecisionManager);}@Overridepublic void init(FilterConfig filterConfig) throws ServletException {}@Overridepublic void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {FilterInvocation fi = new FilterInvocation(request, response, chain);invoke(fi);}public void invoke(FilterInvocation fi) throws IOException, ServletException {
//fi里面有一个被拦截的url
//里面调用MyInvocationSecurityMetadataSource的getAttributes(Object object)这个方法获取fi对应的所有权限
//再调用MyAccessDecisionManager的decide方法来校验用户的权限是否足够InterceptorStatusToken token = super.beforeInvocation(fi);try {
//执行下一个拦截器fi.getChain().doFilter(fi.getRequest(), fi.getResponse());} finally {super.afterInvocation(token, null);}}@Overridepublic void destroy() {}@Overridepublic Class<?> getSecureObjectClass() {return FilterInvocation.class;}@Overridepublic SecurityMetadataSource obtainSecurityMetadataSource() {return this.securityMetadataSource;}
}
package com.programb.example.service;import org.springframework.security.core.GrantedAuthority;public class MyGrantedAuthority implements GrantedAuthority {private String url;private String method;public String getPermissionUrl() {return url;}public void setPermissionUrl(String permissionUrl) {this.url = permissionUrl;}public String getMethod() {return method;}public void setMethod(String method) {this.method = method;}public MyGrantedAuthority(String url, String method) {this.url = url;this.method = method;}@Overridepublic String getAuthority() {return this.url + ";" + this.method;}
}
package com.programb.example.service;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Service;import com.programb.example.dao.PermissionDao;
import com.programb.example.domain.Permission;import javax.servlet.http.HttpServletRequest;
import java.util.*;@Service
public class MyInvocationSecurityMetadataSourceService  implementsFilterInvocationSecurityMetadataSource {//此方法是为了判定用户请求的url 是否在权限表中,如果在权限表中,则返回给 decide 方法,用来判定用户是否有此权限。如果不在权限表中则放行。//因为我不想每一次来了请求,都先要匹配一下权限表中的信息是不是包含此url,// 我准备直接拦截,不管请求的url 是什么都直接拦截,然后在MyAccessDecisionManager的decide 方法中做拦截还是放行的决策。//所以此方法的返回值不能返回 null 此处我就随便返回一下。@Overridepublic Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {Collection<ConfigAttribute> co=new ArrayList<>();co.add(new SecurityConfig("null"));return co;}@Overridepublic Collection<ConfigAttribute> getAllConfigAttributes() {return null;}@Overridepublic boolean supports(Class<?> clazz) {return true;}
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.programb.example.dao.PermissionDao">
<select id="findAll"  resultType="com.programb.example.domain.Permission">SELECT * from Sys_permission ;
</select><select id="findByAdminUserId" parameterType="int" resultType="com.programb.example.domain.Permission">select p.*from Sys_User uLEFT JOIN sys_role_user sru on u.id= sru.Sys_User_idLEFT JOIN Sys_Role r on sru.Sys_Role_id=r.idLEFT JOIN Sys_permission_role spr on spr.role_id=r.idLEFT JOIN Sys_permission p on p.id =spr.permission_idwhere u.id=#{userId}</select></mapper>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.programb.example.dao.UserDao"><resultMap id="userMap" type="com.programb.example.domain.SysUser"><id property="id" column="ID"/><result property="username" column="username"/><result property="password" column="PASSWORD"/><collection property="roles" ofType="com.programb.example.domain.SysRole"><result column="name" property="name"/></collection></resultMap><select id="findByUserName" parameterType="String" resultMap="userMap">select u.*,r.namefrom Sys_User uLEFT JOIN sys_role_user sru on u.id= sru.Sys_User_idLEFT JOIN Sys_Role r on sru.Sys_Role_id=r.idwhere username= #{username}</select>
</mapper>
ms.db.driverClassName=com.mysql.jdbc.Driver
ms.db.url=jdbc:mysql://localhost:3306/cache?characterEncoding=utf-8&useSSL=false
ms.db.username=root
ms.db.password=admin
ms.db.maxActive=500logging.level.org.springframework.security= INFO
spring.thymeleaf.cache=false
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.programb</groupId><artifactId>springboot-security</artifactId><version>1.0-SNAPSHOT</version><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.3.0.RELEASE</version></parent><properties><start-class>com.programb.Application</start-class><maven.compiler.target>1.8</maven.compiler.target><maven.compiler.source>1.8</maven.compiler.source><mybatis.version>3.2.7</mybatis.version><mybatis-spring.version>1.2.2</mybatis-spring.version></properties><dependencies><!--springboot--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency><dependency><groupId>org.thymeleaf.extras</groupId><artifactId>thymeleaf-extras-springsecurity</artifactId></dependency><!--db--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>6.0.5</version></dependency><dependency><groupId>com.mchange</groupId><artifactId>c3p0</artifactId><version>0.9.5.2</version><exclusions><exclusion><groupId>commons-logging</groupId><artifactId>commons-logging</artifactId></exclusion></exclusions></dependency><!--mybatis--><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>${mybatis.version}</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>${mybatis-spring.version}</version></dependency></dependencies></project>
http://www.lbrq.cn/news/1067275.html

相关文章:

  • 个人网站 推荐/站长网站查询
  • 网站开发后台技术/百度百科官网
  • 作it去外包公司好吗/seo云优化平台
  • 北京好的网站建设公司/国家优化防控措施
  • 找人做网站怕侵权/近三年成功的营销案例
  • 南京网站优化网站建设公司/优化营商环境存在问题及整改措施
  • 1000平方办公室装修多少钱/淘宝标题优化网站
  • facebook怎么建设网站/深圳市seo上词贵不贵
  • 网站开发技术方案模板/宁波seo外包公司
  • 忻州 建网站/专业网站推广软件
  • 中华住房与城乡建设厅网站/企业营销策划是做什么的
  • 用php做网站要用构架吗/苏州seo网站公司
  • 生物制药公司网站建设/中国十大电商公司排名
  • 网站的营销方式有哪些/seo 专业
  • 济南网站建设公司哪个好/智谋网站优化公司
  • 网站左侧导航代码/网站域名购买
  • 网站怎么接入百度地图/凡科建站怎么建网站
  • 网站的设计原则/seo关键词优化举例
  • 中企动力网站价格/郑州官网网络营销外包
  • wordpress小工具不能完全显示/菏泽地网站seo
  • 禹城做网站的公司/深圳全网推广排名
  • 服务器怎么做看视频的网站/长春seo排名外包
  • 佛山网站建设佛山网络推广/seo与sem的区别
  • 怎么搭建自己的网站服务器/百度网盘帐号登录入口
  • 广州高端网站设计/疫情放开最新消息今天
  • 网站建设站点无法发布/百度网址大全网站大全
  • 返利淘客网站源码/平台推广方式方法是什么
  • 网站建设中网站需求分析和报告工能论文/网络营销模式下品牌推广研究
  • 效果图哪个网站好/杭州网络推广外包
  • 北京南站到北京站/巨量引擎官网
  • Excel商业智能分析报表 【销售管理分析仪】
  • 更换KR100门禁读头&主机
  • Python Seaborn【数据可视化库】 全面讲解
  • 如果esp_radar_train_stop()调用失败(比如训练未正常启动、持续时间不足、或其他配置未完成),那么:
  • 【2025/08/01】GitHub 今日热门项目
  • 赛思NTP服务器选型推荐,赛思NTP服务器云端助力“数智伊利”步入现实!