Spring Security 用户信息数据源

前面章节中用户名、密码、权限都是写在配置文件里的,不能动态的管理用户的权限,大多数时候显然是不行的。这里介绍从其他数据源读取用户的信息,例如从数据库,LDAP 等。只需要给 authentication-provider 提供接口 UserDetailsService 的实现类即可,使用这个类获取用户的信息,涉及以下内容:
  • 修改 spring-security.xml 中的 authentication-provider
  • 类 UserDetailsService 实现了 Spring Security 的接口 UserDetailsService
  • 类 User
  • 类 UserService
spring-security.xml

修改 authentication-manager 下的 user-service-ref 为我们自定义的 UserDetailsService

    
<?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.xsd
            http://www.springframework.org/schema/security
            http://www.springframework.org/schema/security/spring-security.xsd">
    <beans:bean id="loginSuccessHandler" class="com.xtuer.security.LoginSuccessHandler"/>
    <http security="none" pattern="/static/**"/>
    <http auto-config="true">
        <intercept-url pattern="/admin" access="hasRole('ADMIN')"/>
        <intercept-url pattern="/login" access="permitAll"/>
        <form-login login-page="/login"
                    login-processing-url="/login"
                    default-target-url  ="/"
                    authentication-success-handler-ref="loginSuccessHandler"
                    authentication-failure-url="/login?error"
                    username-parameter="username"
                    password-parameter="password"/>
        <access-denied-handler error-page="/deny" />
        <logout logout-url="/logout" logout-success-url="/login?logout" />
        <csrf disabled="true"/>
    </http>
    <beans:bean id="userDetailsService" class="com.xtuer.security.UserDetailsService"/>
    <authentication-manager>
        <authentication-provider user-service-ref="userDetailsService"/>
    </authentication-manager>
</beans:beans>
UserDetailsService
UserDetailsService 的作用是根据登录表单中用户的用户名查找用户信息用于身份认证。Spring Security 中授权分 2 步:身份验证 (Authentication),权限验证 (Authorization)
  • 用户在登录页面输入 username, password,然后点击登录按钮
  • 方法 loadUserByUsername() 使用 username 查找到用户的信息,如密码,权限等
  • Spring Security 使用查找到的密码和加密后用户输入的密码进行比较,如果相等,则身份验证成功
  • 身份验证成功后,使用用户的权限和页面的访问权限比较,页面的权限配置在 intercept-url

    
package com.xtuer.security;
import com.xtuer.bean.User;
import com.xtuer.service.UserService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
public class UserDetailsService implements org.springframework.security.core.userdetails.UserDetailsService {
    private UserService userService = new UserService();
    /**
     * 使用 username 加载用户的信息,如密码,权限等
     * @param  username 登陆表单中用户输入的用户名
     * @return 返回查找到的用户对象
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.findUserByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException(username + " not found!");
        }
        return user;
    }
}
UserService
UserService 用户查找用户信息
    
package com.xtuer.service;
import com.xtuer.bean.User;
import java.util.HashMap;
import java.util.Map;
public class UserService {
    private static Map<String, User> users = new HashMap<String, User>();
    static {
        // 模拟数据源,可以是多种,如数据库,LDAP,从配置文件读取等
        users.put("admin", new User("admin", "{noop}Passw0rd", "ROLE_ADMIN"));
        users.put("alice", new User("alice", "{noop}Passw0rd", "ROLE_USER"));
    }
    public User findUserByUsername(String username) {
        return users.get(username);
    }
}

User

    
package com.xtuer.bean;
import com.alibaba.fastjson.JSON;
import lombok.Getter;
import lombok.Setter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import java.util.*;
/**
 * 用户类型,根据 userdetails.User 的设计,roles, authorities, expired 等状态不能修改,
 * 只能是创建用户对象的时候传入进来。
 */
@Getter
@Setter
public class User extends org.springframework.security.core.userdetails.User {
    private Long   id;
    private String username;
    private String password;
    private String mail;
    private boolean enabled;
    private Set<String> roles = new HashSet<>(); // 用户的角色
    public User() {
        // 父类不允许空的用户名、密码和权限,所以给个默认的,这样就可以用默认的构造函数创建 User 对象。
        super("non-exist-username", "", new HashSet<>());
    }
    /**
     * 使用账号、密码、角色创建用户
     *
     * @param username 账号
     * @param password 密码
     * @param roles    角色
     */
    public User(String username, String password, String... roles) {
        this(username, password, true, roles);
    }
    /**
     * 使用账号、密码、是否禁用、角色创建用户
     *
     * @param username 账号
     * @param password 密码
     * @param enabled  是否禁用
     * @param roles    角色
     */
    public User(String username, String password, boolean enabled, String... roles) {
        super(username, password, enabled, true, true, true, AuthorityUtils.createAuthorityList(roles));
        this.username = username;
        this.password = password;
        this.enabled  = enabled;
        this.roles.addAll(Arrays.asList(roles));
    }
    /**
     * 用户信息修改后,例如角色修改后不会更新到父类的 authorities 中,需要重新创建一个用户对象才行
     *
     * @param user 已有用户对象
     * @return 新的用户对象,权限等信息更新到了父类的 authorities 中
     */
    public static User userForSpringSecurity(User user) {
        return new User(user.username, user.password, user.enabled, user.getRoles().toArray(new String[0]));
    }
    public static void main(String[] args) {
        User user1 = new User();
        System.out.println(JSON.toJSONString(user1));
        System.out.println(user1.getRoles());
        User user2 = new User("Bob", "Passw0rd", "ROLE_USER", "ROLE_ADMIN");
        System.out.println(JSON.toJSONString(user2));
        System.out.println(user2.getRoles());
    }
}

测试

访问 http://localhost:8080/hello
访问 http://localhost:8080/admin
输入错误的用户名或密码,观察登陆失败的页面
输入正确的用户名和密码,继续登陆
访问 http://localhost:8080/logout,观察注销成功的页面
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,569评论 4 363
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,499评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,271评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,087评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,474评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,670评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,911评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,636评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,397评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,607评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,093评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,418评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,074评论 3 237
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,092评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,865评论 0 196
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,726评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,627评论 2 270

推荐阅读更多精彩内容