`

spring security权限管理

阅读更多

spring security以前叫acegi是一个非常棒的权限管理框架,下面介绍一下如何配置:

1.导入jar包,见附件;

2.web.xml中添加

 

<filter>

<filter-name>springSecurityFilterChain</filter-name>

<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>

</filter>

<filter-mapping>

<filter-name>springSecurityFilterChain</filter-name>

<url-pattern>/*</url-pattern>

</filter-mapping>

3.applicationContext_security.xml配置文件

 

<?xml version="1.0" encoding="UTF-8"?>

 

<beans:beans xmlns="http://www.springframework.org/schema/security"

    xmlns:beans="http://www.springframework.org/schema/beans"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd

                        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">

    <!--不过滤css、js、图片等 -->

    <http pattern="/css/**" security="none"/>

    <http pattern="/img/**" security="none"/>

    <http pattern="/js/**" security="none"/>

 

<http pattern="/**" access-denied-page="/404.jsp">

<intercept-url pattern="/login*" access="IS_AUTHENTICATED_ANONYMOUSLY"/>

<intercept-url pattern="/user/**" access="ROLE_ADMIN"/>

<remember-me/>

<form-login login-page="/login.html" default-target-url="/index.html"/>

<logout logout-url="/logout" logout-success-url="/login.html"/>

<session-management invalid-session-url="/login.html" session-authentication-error-url="/login.html"/>

</http>

 

<authentication-manager>

<authentication-provider user-service-ref="myJdbcDaoImpl"> 

                       <!--密码MD5加密,用户名做盐值 -->

<password-encoder hash="md5">

<salt-source user-property="username"/>

</password-encoder>

</authentication-provider> 

</authentication-manager>

        <!--重写JdbcDaoImpl -->

<beans:bean id="myJdbcDaoImpl" class="cn.investide.security.MyJdbcDaoImpl">

<beans:property name="dataSource" ref="dataSource"></beans:property>

</beans:bean>

</beans:beans>

 

MyJdbcDaoImpl内容如下:

public class MyJdbcDaoImpl extends JdbcDaoSupport implements UserDetailsService {

 

        //根据你的数据库修改sql语句

public static final String DEF_USERS_BY_USERNAME_QUERY = "select user_id,username,real_name,password,enabled from users WHERE username = ? ";

public static final String DEF_AUTHORITIES_BY_USERNAME_QUERY = "select u.username,a.authority_name as authorities "

+ "from authority a,users u,user_role_mapping ur,role_authority_mapping ra "

+ "where u.user_id=ur.user_id "

+ "and ur.role_id=ra.role_id "

+ "and ra.authority_id=a.authority_id and username=? ";

public static final String DEF_GROUP_AUTHORITIES_BY_USERNAME_QUERY = "select g.id, g.group_name, ga.authority "

+ "from groups g, group_members gm, group_authorities ga "

+ "where gm.username = ? "

+ "and g.id = ga.group_id "

+ "and g.id = gm.group_id";

 

 

 

protected MessageSourceAccessor messages = SpringSecurityMessageSource

.getAccessor();

 

private String authoritiesByUsernameQuery;

private String groupAuthoritiesByUsernameQuery;

private String usersByUsernameQuery;

private String rolePrefix = "";

private boolean usernameBasedPrimaryKey = true;

private boolean enableAuthorities = true;

private boolean enableGroups

 

public MyJdbcDaoImpl() {

usersByUsernameQuery = DEF_USERS_BY_USERNAME_QUERY;

authoritiesByUsernameQuery = DEF_AUTHORITIES_BY_USERNAME_QUERY;

groupAuthoritiesByUsernameQuery = DEF_GROUP_AUTHORITIES_BY_USERNAME_QUERY;

}

 

protected void addCustomAuthorities(String username,

List<GrantedAuthority> authorities) {

}

 

public String getUsersByUsernameQuery() {

return usersByUsernameQuery;

}

 

protected void initDao() throws ApplicationContextException {

Assert.isTrue(enableAuthorities || enableGroups,

"Use of either authorities or groups must be enabled");

}

 

public MyUserDetails loadUserByUsername(String username)

throws UsernameNotFoundException, DataAccessException {

List<UserDetails> users = loadUsersByUsername(username);

 

if (users.size() == 0) {

logger.debug("Query returned no results for user '" + username

+ "'");

 

throw new UsernameNotFoundException(messages.getMessage(

"JdbcDaoImpl.notFound", new Object[] { username },

"Username {0} not found"), username);

}

 

UserDetails user = users.get(0); // contains no GrantedAuthority[]

 

Set<GrantedAuthority> dbAuthsSet = new HashSet<GrantedAuthority>();

 

if (enableAuthorities) {

dbAuthsSet.addAll(loadUserAuthorities(user.getUsername()));

}

 

if (enableGroups) {

dbAuthsSet.addAll(loadGroupAuthorities(user.getUsername()));

}

 

List<GrantedAuthority> dbAuths = new ArrayList<GrantedAuthority>(

dbAuthsSet);

 

addCustomAuthorities(user.getUsername(), dbAuths);

 

if (dbAuths.size() == 0) {

logger.debug("User '" + username

+ "' has no authorities and will be treated as 'not found'");

 

throw new UsernameNotFoundException(messages.getMessage(

"JdbcDaoImpl.noAuthority", new Object[] { username },

"User {0} has no GrantedAuthority"), username);

}

 

return createUserDetails(username, (MyUserDetails) user, dbAuths);

}

 

 

protected List<UserDetails> loadUsersByUsername(String username) {

return getJdbcTemplate().query(usersByUsernameQuery,

new String[] { username }, new RowMapper<UserDetails>() {

public UserDetails mapRow(ResultSet rs, int rowNum)

throws SQLException {

int userId = rs.getInt(1);

String username = rs.getString(2);

String realname = rs.getString(3);

String password = rs.getString(4);

boolean enabled = rs.getBoolean(5);

UserDetails myUser = new MyUser(userId, username,realname,

password, enabled, true, true, true,

AuthorityUtils.NO_AUTHORITIES);

return myUser;

}

 

});

}

 

 

protected List<GrantedAuthority> loadUserAuthorities(String username) {

return getJdbcTemplate().query(authoritiesByUsernameQuery,

new String[] { username }, new RowMapper<GrantedAuthority>() {

public GrantedAuthority mapRow(ResultSet rs, int rowNum)

throws SQLException {

String roleName = rolePrefix + rs.getString(2);

GrantedAuthorityImpl authority = new GrantedAuthorityImpl(

roleName);

 

return authority;

}

});

}

 

 

protected List<GrantedAuthority> loadGroupAuthorities(String username) {

return getJdbcTemplate().query(groupAuthoritiesByUsernameQuery,

new String[] { username }, new RowMapper<GrantedAuthority>() {

public GrantedAuthority mapRow(ResultSet rs, int rowNum)

throws SQLException {

String roleName = getRolePrefix() + rs.getString(3);

GrantedAuthorityImpl authority = new GrantedAuthorityImpl(

roleName);

 

return authority;

}

});

}

 

 

protected MyUserDetails createUserDetails(String username,

MyUserDetails userFromUserQuery,

List<GrantedAuthority> combinedAuthorities) {

int returnUserId = userFromUserQuery.getUserId();

String returnUsername = userFromUserQuery.getUsername();

String returnRealname = userFromUserQuery.getRealname();

 

if (!usernameBasedPrimaryKey) {

returnUsername = username;

}

 

MyUserDetails myUser = new MyUser(returnUserId, returnUsername, returnRealname,

userFromUserQuery.getPassword(), userFromUserQuery.isEnabled(),

true, true, true, combinedAuthorities);

 

return myUser;

}

 

 

public void setAuthoritiesByUsernameQuery(String queryString) {

authoritiesByUsernameQuery = queryString;

}

 

protected String getAuthoritiesByUsernameQuery() {

return authoritiesByUsernameQuery;

}

 

 

public void setGroupAuthoritiesByUsernameQuery(String queryString) {

groupAuthoritiesByUsernameQuery = queryString;

}

 

 

public void setRolePrefix(String rolePrefix) {

this.rolePrefix = rolePrefix;

}

 

protected String getRolePrefix() {

return rolePrefix;

}

 

 

public void setUsernameBasedPrimaryKey(boolean usernameBasedPrimaryKey) {

this.usernameBasedPrimaryKey = usernameBasedPrimaryKey;

}

 

protected boolean isUsernameBasedPrimaryKey() {

return usernameBasedPrimaryKey;

}

 

 

public void setUsersByUsernameQuery(String usersByUsernameQueryString) {

this.usersByUsernameQuery = usersByUsernameQueryString;

}

 

protected boolean getEnableAuthorities() {

return enableAuthorities;

}

 

 

public void setEnableAuthorities(boolean enableAuthorities) {

this.enableAuthorities = enableAuthorities;

}

 

protected boolean getEnableGroups() {

return enableGroups;

}

 

 

public void setEnableGroups(boolean enableGroups) {

this.enableGroups = enableGroups;

}

}

 

注意,以上源码中我自己增加了userId

扩展MyUserDetails

public interface MyUserDetails extends Serializable,UserDetails{

// ~ Methods

// ========================================================================================================

 

int getUserId();

 

/**

* Returns the authorities granted to the user. Cannot return

* <code>null</code>.

* @return the authorities, sorted by natural key (never <code>null</code>)

*/

Collection<GrantedAuthority> getAuthorities();

 

/**

* Returns the password used to authenticate the user. Cannot return

* <code>null</code>.

* @return the password (never <code>null</code>)

*/

String getPassword();

 

/**

* Returns the username used to authenticate the user. Cannot return

* <code>null</code>.

* @return the username (never <code>null</code>)

*/

String getUsername();

 

String getRealname();

 

/**

* Indicates whether the user's account has expired. An expired account

* cannot be authenticated.

* @return <code>true</code> if the user's account is valid (ie

*         non-expired), <code>false</code> if no longer valid (ie expired)

*/

boolean isAccountNonExpired();

 

/**

* Indicates whether the user is locked or unlocked. A locked user cannot be

* authenticated.

* @return <code>true</code> if the user is not locked, <code>false</code>

*         otherwise

*/

boolean isAccountNonLocked();

 

/**

* Indicates whether the user's credentials (password) has expired. Expired

* credentials prevent authentication.

* @return <code>true</code> if the user's credentials are valid (ie

*         non-expired), <code>false</code> if no longer valid (ie expired)

*/

boolean isCredentialsNonExpired();

 

/**

* Indicates whether the user is enabled or disabled. A disabled user cannot

* be authenticated.

* @return <code>true</code> if the user is enabled, <code>false</code>

*         otherwise

*/

boolean isEnabled();

}

扩展MyUser

public class MyUser implements MyUserDetails, CredentialsContainer {

// ~ Instance fields

// ================================================================================================

private int userId;

private String password;

private final String username;

private final String realname;

private final Set<GrantedAuthority> authorities;

private final boolean accountNonExpired;

private final boolean accountNonLocked;

private final boolean credentialsNonExpired;

private final boolean enabled;

 

// ~ Constructors

// ===================================================================================================

 

/**

* @deprecated

*/

public MyUser(int userId, String username,String realname, String password,

boolean enabled, boolean accountNonExpired,

boolean credentialsNonExpired, boolean accountNonLocked,

GrantedAuthority[] authorities) {

this(userId, username, realname, password, enabled, accountNonExpired,

credentialsNonExpired, accountNonLocked,

authorities == null ? null : Arrays.asList(authorities));

}

 

/**

* Construct the <code>User</code> with the details required by

* {@link org.springframework.security.authentication.dao.DaoAuthenticationProvider}

* .

* @param username

*            the username presented to the

*            <code>DaoAuthenticationProvider</code>

* @param password

*            the password that should be presented to the

*            <code>DaoAuthenticationProvider</code>

* @param enabled

*            set to <code>true</code> if the user is enabled

* @param accountNonExpired

*            set to <code>true</code> if the account has not expired

* @param credentialsNonExpired

*            set to <code>true</code> if the credentials have not expired

* @param accountNonLocked

*            set to <code>true</code> if the account is not locked

* @param authorities

*            the authorities that should be granted to the caller if they

*            presented the correct username and password and the user is

*            enabled. Not null.

* @throws IllegalArgumentException

*             if a <code>null</code> value was passed either as a parameter

*             or as an element in the <code>GrantedAuthority</code>

*             collection

*/

public MyUser(int userId, String username, String realname, String password,

boolean enabled, boolean accountNonExpired,

boolean credentialsNonExpired, boolean accountNonLocked,

Collection<? extends GrantedAuthority> authorities) {

 

if (((username == null) || "".equals(username)) || (password == null)) {

throw new IllegalArgumentException(

"Cannot pass null or empty values to constructor");

}

this.userId = userId;

this.username = username;

this.realname = realname;

this.password = password;

this.enabled = enabled;

this.accountNonExpired = accountNonExpired;

this.credentialsNonExpired = credentialsNonExpired;

this.accountNonLocked = accountNonLocked;

this.authorities = Collections

.unmodifiableSet(sortAuthorities(authorities));

}

 

// ~ Methods

// ========================================================================================================

 

public Collection<GrantedAuthority> getAuthorities() {

return authorities;

}

 

public String getPassword() {

return password;

}

 

public int getUserId() {

return userId;

}

 

public String getUsername() {

return username;

}

 

public String getRealname() {

return realname;

}

 

public boolean isEnabled() {

return enabled;

}

 

public boolean isAccountNonExpired() {

return accountNonExpired;

}

 

public boolean isAccountNonLocked() {

return accountNonLocked;

}

 

public boolean isCredentialsNonExpired() {

return credentialsNonExpired;

}

 

public void eraseCredentials() {

password = null;

}

 

private static SortedSet<GrantedAuthority> sortAuthorities(

Collection<? extends GrantedAuthority> authorities) {

Assert.notNull(authorities,

"Cannot pass a null GrantedAuthority collection");

// Ensure array iteration order is predictable (as per

// UserDetails.getAuthorities() contract and SEC-717)

SortedSet<GrantedAuthority> sortedAuthorities = new TreeSet<GrantedAuthority>(

new AuthorityComparator());

 

for (GrantedAuthority grantedAuthority : authorities) {

Assert.notNull(grantedAuthority,

"GrantedAuthority list cannot contain any null elements");

sortedAuthorities.add(grantedAuthority);

}

 

return sortedAuthorities;

}

 

private static class AuthorityComparator implements

Comparator<GrantedAuthority>, Serializable {

public int compare(GrantedAuthority g1, GrantedAuthority g2) {

// Neither should ever be null as each entry is checked before

// adding it to the set.

// If the authority is null, it is a custom authority and should

// precede others.

if (g2.getAuthority() == null) {

return -1;

}

 

if (g1.getAuthority() == null) {

return 1;

}

 

return g1.getAuthority().compareTo(g2.getAuthority());

}

}

 

/**

* Returns {@code true} if the supplied object is a {@code User} instance

* with the same {@code username} value.

* <p>

* In other words, the objects are equal if they have the same username,

* representing the same principal.

*/

 

public boolean equals(Object rhs) {

if (rhs instanceof MyUser) {

return username.equals(((MyUser) rhs).username);

}

return false;

}

 

/**

* Returns the hashcode of the {@code username}.

*/

 

public int hashCode() {

return username.hashCode();

}

 

 

public String toString() {

StringBuilder sb = new StringBuilder();

sb.append(super.toString()).append(": ");

sb.append("UserId: ").append(this.userId).append("; ");

sb.append("Username: ").append(this.username).append("; ");

sb.append("Realname: ").append(this.realname).append("; ");

sb.append("Password: [PROTECTED]; ");

sb.append("Enabled: ").append(this.enabled).append("; ");

sb.append("AccountNonExpired: ").append(this.accountNonExpired)

.append("; ");

sb.append("credentialsNonExpired: ").append(this.credentialsNonExpired)

.append("; ");

sb.append("AccountNonLocked: ").append(this.accountNonLocked)

.append("; ");

 

if (!authorities.isEmpty()) {

sb.append("Granted Authorities: ");

 

boolean first = true;

for (GrantedAuthority auth : authorities) {

if (!first) {

sb.append(",");

}

first = false;

 

sb.append(auth);

}

} else {

sb.append("Not granted any authorities");

}

 

return sb.toString();

}

}

 

 

在程序中获取用户信息:

MyUserDetails userDetails = (MyUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

int userId=userDetails.getUserId();

在页面中获取用户信息:

<sec:authentication property="principal.realname"></sec:authentication>

 

 

 

分享到:
评论

相关推荐

    SpringSecurity权限管理

    在"SpringSecurity权限管理开发手册.pdf"和"SpringSecurity权限管理开发手册.pdf.txt"中,你将找到更多关于如何配置和使用SpringSecurity进行权限管理的详细信息,包括配置XML或Java配置、定义访问规则、处理未授权...

    Spring Security权限管理开发手册

    ### Spring Security权限管理开发手册知识点概述 #### 一、序言 - **为什么选择Spring Security:** - **安全性:** 提供了强大的安全性保障,包括认证(Authentication)、授权(Authorization)以及会话管理(Session...

    spring security权限管理开发手册及实例.rar

    这个“spring security权限管理开发手册及实例.rar”压缩包显然包含了关于如何使用Spring Security进行权限管理的详细指南和实际操作示例。让我们深入探讨一下Spring Security的核心概念、功能以及如何在实践中应用...

    Spring Security 基于数据库的权限管理配置

    在基于数据库的权限管理配置中,Spring Security 允许我们存储、管理和验证用户的访问权限,这使得权限控制更加灵活和可扩展。下面将详细阐述如何进行Spring Security的数据库权限管理配置。 1. **配置数据源** 在...

    Spring Security 权限管理手册 chm中文版

    Spring Security 权限管理手册 chm中文版

    Spring Security 安全权限管理手册(最新)

    《Spring Security安全权限管理手册》是一份针对Spring Security框架的详尽指南,旨在为初学者提供全面而深入的理解。Spring Security作为Spring框架的一个重要组成部分,它提供了强大的安全性和访问控制功能,是...

    SpringSecurity权限管理系统实战 主要页面及接口实现.docx

    首先,我们注意到标题提及的是“SpringSecurity权限管理系统实战”,这表明我们将讨论如何在实际项目中应用SpringSecurity来管理用户的权限。权限管理系统通常包括用户角色、权限分配、资源保护等功能,Spring...

    Spring security认证授权

    它提供了全面的安全解决方案,包括用户认证、权限授权、会话管理、CSRF防护以及基于HTTP的访问控制。在这个例子中,我们将深入探讨如何使用Spring Security进行认证和授权,并结合数据库操作进行动态配置。 首先,...

    Spring Security安全权限管理手册.CHM

    Spring Security安全权限管理手册.CHM

    springboot springsecurity动态权限控制

    在这个“springboot springsecurity动态权限控制”的主题中,我们将深入探讨如何在Spring Boot项目中集成Spring Security,实现动态权限控制,让菜单权限的管理更加灵活和高效。 首先,我们需要理解Spring Security...

    spring security实现动态授权

    总的来说,Spring Security的动态授权功能使得权限管理变得更加灵活和高效。通过对源代码的适当修改,我们可以构建一个完全可配置的权限管理系统,适应不断变化的业务需求。这个过程涉及多个组件的定制,但一旦设置...

    SpringSecurity权限管理系统日志、接口文档等实现.docx

    综上所述,这个项目涵盖了Spring Security权限管理的基础设置,以及Spring Boot的一些实用特性,如自定义启动Banner、日志记录、API文档生成和数据库连接池配置。这些知识点对于构建一个健壮的、易于维护的后端服务...

    Spring Security in Action

    Spring Security 是一个基于 Java 的安全框架,旨在提供身份验证、授权和访问控制等功能。下面是 Spring Security 的主要知识点: 一、身份验证(Authentication) 身份验证是指对用户身份的验证,以确保用户的...

    Spring Security 资料合集

    Spring Security 是一个强大的安全框架,主要用于Java应用的安全管理,它为Web应用和企业级应用提供了全面的安全服务。这个框架能够处理认证、授权以及各种安全相关的功能,帮助开发者构建安全、可扩展的应用。以下...

    spring security 安全权限管理手册

    ### Spring Security 安全权限管理手册 #### 第一部分:基础篇 ##### 第1章:一个简单的 HelloWorld 在这一章节中,我们将了解如何搭建一个最基础的 Spring Security 项目,并通过一个简单的示例来理解 Spring ...

Global site tag (gtag.js) - Google Analytics