最近公司要做开发平台,对安全要求比较高;SPRING SECURTIY框架刚好对所有安全问题都有涉及,框架的作者最近还做了spring-session项目实现分布式会话管理,还有他的另一个开源项目spring-security-oauth2。
关于spring-security的配置方法,网上有非常多的介绍,大都是基于XML配置,配置项目非常多,阅读和扩展都不方便。其实spring-security也有基于java的配置方式,今天就讲讲如何通过java配置方式,扩展spring-security实现权限配置全部从表中读取。
直接上代码:
application.properties配置文件
- privilesByUsernameQuery= select authority from user_authorities where username = ?
- allUrlAuthoritiesQuery=SELECT authority_id , url FROM Url_Authorities
javaconfig
1.读取数据库中的URL资源对应的权限列表 2.读取登录用户拥有的权限列表
- package com.sivalabs.springapp.config;
-
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.util.List;
-
- import org.springframework.jdbc.core.RowMapper;
- import org.springframework.security.core.GrantedAuthority;
- import org.springframework.security.core.authority.SimpleGrantedAuthority;
- import org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl;
-
- import com.sivalabs.springapp.entities.UrlAuthority;
-
-
- public class CustomUserDetailsService extends JdbcDaoImpl{
-
- private String allUrlAuthoritiesQuery ;
-
-
-
- public List<UrlAuthority> loadUrlAuthorities( ) {
- return getJdbcTemplate().query(allUrlAuthoritiesQuery, new RowMapper<UrlAuthority>() {
- public UrlAuthority mapRow(ResultSet rs, int rowNum) throws SQLException {
- return new UrlAuthority (rs.getInt(1),rs.getString(2));
- }
- });
- }
-
-
-
- protected List<GrantedAuthority> loadUserAuthorities(String username) {
- return getJdbcTemplate().query(super.getAuthoritiesByUsernameQuery(), new String[] {username}, new RowMapper<GrantedAuthority>() {
- public GrantedAuthority mapRow(ResultSet rs, int rowNum) throws SQLException {
- String roleName = rs.getString(1);
- return new SimpleGrantedAuthority(roleName);
- }
- });
- }
-
- public void setAllUrlAuthoritiesQuery(String allUrlAuthoritiesQuery) {
- this.allUrlAuthoritiesQuery = allUrlAuthoritiesQuery;
- }
-
- }
测试数据及案例见 http://note.youdao.com/share/?id=c20e348d9a08504cd3ac1c7c58d1026e&type=note
spring-security-oauth2 http://www.mvnrepository.com/artifact/org.springframework.security.oauth/spring-security-oauth2
Maven Repository: org.springframework.session » spring-session http://www.mvnrepository.com/artifact/org.springframework.session/spring-session