spring-security-3.0.3. 与Spring3.0.3 集成配置配置说明<二>

本文介绍了一个具体的Spring Security权限管理系统实现方案,包括加载数据库中的权限配置、认证用户及验证码验证等功能。通过对FilterInvocationSecurityMetadataSource、UserDetailsService及UsernamePasswordAuthenticationFilter等类的自定义实现,达到了对用户权限的有效管理。
3. 实现类

3.1 加载数据库中的权限,也要实现FilterInvocationSecurityMetadataSource类

package com.bestsoft.ssh.service.impl.security;



/**

* 加载所有的权限配置

* @author zhangchaobing

*

*/

public class InvocationSecurityMetadataSourceService implements FilterInvocationSecurityMetadataSource {



//注入自己的DAO

@Resource(name="basicAuthoritiesHibernateDAO")

private IBasicAuthoritiesDAO basicAuthoritiesHibernateDAO;



private static Map<String, Collection<ConfigAttribute>> resourceMap = null;

private UrlMatcher urlMatcher = new AntUrlPathMatcher();





/**此法方法会在启动时 被调用**/

public void loadResourceDefine()throws Exception {

this.resourceMap = new HashMap<String, Collection<ConfigAttribute>>();



//查询数据库权限配置表

List<BasicAuthorities> authoritiesList = basicAuthoritiesHibernateDAO.findAllByDeleteFlag();

for(int i=0;i<authoritiesList.size();i++){

BasicAuthorities url = (BasicAuthorities)authoritiesList.get(i);

String antPath = url.getUrl();//需要验证的URL

String token = url.getToken();//拥有此处权限才能访问URl



Collection<ConfigAttribute> atts = new ArrayList<ConfigAttribute>();

ConfigAttribute ca = new SecurityConfig(token);

atts.add(ca);



this.resourceMap.put(antPath, atts);

}

System.out.println("---加载所有的权限配置---");

/*//通过硬编码设置,resouce和role

resourceMap = new HashMap<String, Collection<ConfigAttribute>>();

Collection<ConfigAttribute> atts = new ArrayList<ConfigAttribute>();

ConfigAttribute ca = new SecurityConfig("/ROLE_ADD");

atts.add(ca);

resourceMap.put("/jsp/admin.jsp", atts);

*/



}



// According to a URL, Find out permission configuration of this URL.

public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {

if (logger.isDebugEnabled()) {

logger.debug("getAttributes(Object) - start"); //$NON-NLS-1$

}

// guess object is a URL.

String url = ((FilterInvocation) object).getRequestUrl();

Iterator<String> ite = resourceMap.keySet().iterator();

while (ite.hasNext()) {

String resURL = ite.next();

if (urlMatcher.pathMatchesUrl(url, resURL)) {

Collection<ConfigAttribute> returnCollection = resourceMap.get(resURL);

if (logger.isDebugEnabled()) {

logger.debug("getAttributes(Object) - end"); //$NON-NLS-1$

}

return returnCollection;

}

}

if (logger.isDebugEnabled()) {

logger.debug("getAttributes(Object) - end"); //$NON-NLS-1$

}



return null;

}



public boolean supports(Class<?> clazz) {

return true;

}

public Collection<ConfigAttribute> getAllConfigAttributes() {



Set<ConfigAttribute> allAttributes = new HashSet<ConfigAttribute>();

for (Map.Entry<String, Collection<ConfigAttribute>> entry : resourceMap.entrySet()) {

for (ConfigAttribute attrs : entry.getValue()) {

allAttributes.add(attrs);

}

}

return allAttributes;

}



public IBasicAuthoritiesDAO getBasicAuthoritiesHibernateDAO() {

return basicAuthoritiesHibernateDAO;

}

public void setBasicAuthoritiesHibernateDAO(

IBasicAuthoritiesDAO basicAuthoritiesHibernateDAO) {

this.basicAuthoritiesHibernateDAO = basicAuthoritiesHibernateDAO;

}





}

3.2认证用户实现UserDetailsService类类

package com.bestsoft.ssh.service.impl.security;

/**

* 查询用户和用户对应的权限

* @author zhangchaobing

*

*/

public class UserDetailServiceImpl implements UserDetailsService {

@Resource(name="basicUserHibernateDAO")

private IBasicUsersDAO basicUserHibernateDAO;



public UserDetails loadUserByUsername(String username){

try{

//查询用户

BasicUsers user = basicUserHibernateDAO.getBasicUser(username);

BasicUsers returnUser = null;

if(user !=null || !user.equals("")){



returnUser = new BasicUsers(user.getUserId(),user.getUsername(),user.getPassword(),getAuthorities(user.getUserId()),DateTime.getStringDate());

}

return returnUser;

}catch (DataAccessException repositoryProblem) {

repositoryProblem.printStackTrace();

throw new AuthenticationServiceException("数据连接失败,服务器忙,请稍后再试");

}

}

//加载用户对应的权限

public List<GrantedAuthority> getAuthorities(int userId) {

List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

authorities.add(new GrantedAuthorityImpl("ROLE_ANONYMOUS")); //赋予一个临时权限

return authorities;

}

}



3.3为了实现对验证码的验证,这里重写登陆验证Filter 继承

UsernamePasswordAuthenticationFilter类



package com.bestsoft.ssh.service.impl.security;



/**

* 验证用户信息

* @author zhangchaobing

*

*/

public class ValidateCodeUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter{



public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {



//zcb 添加对验证码验证

checkValidateCode(request);

return super.attemptAuthentication( request, response);

}



/**

* 验证 验证码

* @param request

*/

protected void checkValidateCode(HttpServletRequest request) {

String sessionValidateCode = (String) request.getSession().getAttribute("rand");

String validateCodeParameter = request.getParameter("randNum");



if (StringUtils.isEmpty(validateCodeParameter)|| StringUtils.isEmpty(sessionValidateCode) || !sessionValidateCode.equalsIgnoreCase(validateCodeParameter)) {

throw new AuthenticationServiceException("验证码不正确!");

}



}



/**

* 重写父类的方法,在验证用户完成调用的方法

*/

protected void successfulAuthentication(

HttpServletRequest arg0, HttpServletResponse arg1,

Authentication arg2) throws IOException, ServletException {



String username = obtainUsername(arg0);

arg0.getSession().setAttribute("userName",arg0.getParameter("j_username"));

super.successfulAuthentication(arg0, arg1, arg2);

}



}





4. 总结

对于spring securiyt3.0的默认配置很简单,但是为了满足系统的需求是需要重写很多配置的,一般需要好好研究一下源码,才能明白

注:关于<一>的配置没有通过网易审核,不知道网易怎么搞的
升级mybatis-plus 要求使用阿里云下载<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>3.4.7</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>takeoutsystem</artifactId> <version>0.0.1-SNAPSHOT</version> <name>takeoutsystem</name> <description>takeoutsystem</description> <properties> <java.version>17</java.version> <!-- MyBatis Plus 版本 --> <mybatis-plus.version>3.5.6</mybatis-plus.version> <!-- 其他依赖版本 --> <jjwt.version>0.11.5</jjwt.version> <springdoc-openapi.version>2.8.5</springdoc-openapi.version> <thymeleaf-extras-springsecurity6.version>3.1.2.RELEASE</thymeleaf-extras-springsecurity6.version> </properties> <dependencies> <!-- Spring Boot 基础依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>3.0.3</version> <!-- 匹配Spring Boot 3.x --> </dependency> <!-- MyBatis Plus Starter (替换原生MyBatis) --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>${mybatis-plus.version}</version> </dependency> <!-- 数据库依赖 --> <dependency> <groupId>com.mysql</groupId> <artifactId>mysql-connector-j</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>test</scope> </dependency> <!-- 安全认证依赖 --> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-api</artifactId> <version>${jjwt.version}</version> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-impl</artifactId> <version>${jjwt.version}</version> <scope>runtime</scope> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt-jackson</artifactId> <version>${jjwt.version}</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-springsecurity6</artifactId> <version>${thymeleaf-extras-springsecurity6.version}</version> </dependency> <!-- API文档 --> <dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId> <version>${springdoc-openapi.version}</version> </dependency> <!-- 测试依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <scope>provided</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <excludes> <exclude> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </exclude> </excludes> </configuration> </plugin> </plugins> </build> </project> 修改后给出全部代码
07-17
<?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> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.7.14</version> <relativePath/> </parent> <groupId>com.film</groupId> <artifactId>film-website</artifactId> <version>1.0.0</version> <name>film-website</name> <description>Online Film Website with Spring Boot</description> <properties> <java.version>8</java.version> <maven.compiler.source>8</maven.compiler.source> <maven.compiler.target>8</maven.compiler.target> </properties> <dependencies> <!-- Spring Boot Starter Web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Spring Boot Starter Data JPA --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!-- MyBatis Spring Boot Starter --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.3.1</version> </dependency> <!-- MySQL Driver --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!-- Spring Boot Starter Validation --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency> <!-- Spring Boot Starter Security --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <!-- JSON Web Token --> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.1</version> </dependency> <!-- File Upload --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.4</version> </dependency> <!-- Apache Commons IO --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.11.0</version> </dependency> <!-- Spring Boot DevTools --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <!-- Spring Boot Test --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- Security Test --> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> 这是我的pom文件,怎么修改版本
最新发布
09-02
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值