您的位置:首页 > 博客中心 > 数据库 >

Spring Security 3 (三) 用户数据存放于数据库

时间:2022-03-10 17:08

上章回顾:

上一章中,我们将用户名、密码以及用户对应的角色都配置于applicationContext-security.xml中,基本实现了我们能控制用户的访问权限。但是在现实开发中,我们不可能将用户信息硬编码在配置文件中,通常我们都是存放到数据中。同时我们应该对用户的密码进行加密存储。


目标:


4.到此,基本已经搞定。现在我们只需用修改配置文件,告诉SpringSecurity按照我们自己定义的方法来实现,修改applicationContext-security.xml:

<authentication-manager>
        <authentication-provider user-service-ref="userService">
            <password-encoder ref="passwordEncoder">
                <salt-source ref="saltSource"/>
            </password-encoder>
        </authentication-provider>
    </authentication-manager>
    <!-- 密码盐值,取用户名作为盐值 -->
      <!-- userPropertyToUse:主要用来将我们的对象放入到他的方法中,根据这个属性名称取出盐值 -->
    <beans:bean id="saltSource"
        class="org.springframework.security.authentication.dao.ReflectionSaltSource">
        <beans:property name="userPropertyToUse" value="salt_value"></beans:property>
    </beans:bean>
    <!-- SHA加密类 -->
    <beans:bean id="passwordEncoder"
        class="org.springframework.security.authentication.encoding.ShaPasswordEncoder">
    </beans:bean>

我们通过使用SpringSecurity提供的加密方法进行加密,同时我们增加盐值在密码中,这样让破解失效。

authentication-provider中user-service-ref,就是我们上一点中自定义的service类。同时我们提供加密方式。


5.在此我们有一个问题,如果我们手工的加入数据到数据库中,密码是明文,没有进行加密的。为了我们能够顺利登陆,我们设计一个注册用户的页面,用来注册用户。注册用户页面我们就自己发挥了,主要传递到后台的数据包括:用户名、密码、角色。此点主要是看看如何对密码进行加密:

/**
 * 注入两个工具类
 */
@Resource
private ReflectionSaltSource saltSource;
                  
@Resource
private ShaPasswordEncoder passwordEncoder;
/**
 * 注册用户
 * @param user
 * @return
*/
@RequestMapping("/register")
public ModelAndView register(User user) {
    user.setEnabled(true);
    // 使用系统当前时间作为盐值
    user.setSalt_value(System.currentTimeMillis() + "");
    // 加密密码:原有密码+盐值。盐值通过从user对象中获取,我们在配置中有写到查找哪个属性
    String password = passwordEncoder.encodePassword(user.getPassword(), saltSource.getSalt(user));
    user.setPassword(password);
    if (userDao.addUser(user)) {
            System.out.println("register success");
    } else {
        System.out.println("failed");
    }
    return new ModelAndView("redirect:/login.jsp");
}


6.好了,用户我们注册成功,可以直接跳转到登录页面,用刚才注册的用户名和密码进行登录,并进行权限测试。



本文出自 “” 博客,请务必保留此出处

Spring Security 3 (三) 用户数据存放于数据库,布布扣,bubuko.com

热门排行

今日推荐

热门手游