Spring-Security自定义认证类,显示用户名,BCrypt密码加密

自定义认证类

创建UserDetailsServiceImpl.java 实现 UserDetailsService 接口

添加get set方法,重写loadUserByUsername方法

package com.zym.shop.service;
import java.util.ArrayList;
import java.util.List;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.kaola.pojo.TbSeller;
import com.kaola.sellergoods.service.SellerService;



public class UserDetailServiceImpl implements UserDetailsService {
	
    private SellerService sellerService;
    
	public void setSellerService(SellerService sellerService) {
		this.sellerService = sellerService;
	}
	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {

		List<GrantedAuthority> authorities=new ArrayList<>();
		authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
	
		//根据id来查询用户名
		TbSeller seller = sellerService.findOne(username);

		if(seller==null){
			return  null;
		}
		if(!seller.getStatus().equals("1")){
			return null;
		}
		return new User(username, seller.getPassword(), authorities);
	}

}


配置文件

spring-security.xml


<?xml version="1.0" encoding="UTF-8"?>
<bean:beans xmlns="http://www.springframework.org/schema/security"
            xmlns:bean="http://www.springframework.org/schema/beans"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
            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 http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd">

<!-- 配置放行资源 -->
    <!--<http  pattern="/seller/*" security="none"></http>-->
    <!--<http  pattern="/login/name.do" security="none"></http>-->
    <http  pattern="/login.html" security="none"></http>
    <http  pattern="/register.html" security="none"></http>
    <http  pattern="/login_error.html" security="none"></http>
    <http  pattern="/css/**" security="none"></http>
    <http  pattern="/img/**" security="none"></http>
    <http  pattern="/js/**" security="none"></http>
    <http  pattern="/plugins/**" security="none"></http>


<!-- 配置拦截资源  -->
<http>
   <!-- 拦截路径    "/*"拦截根目录下所有资源   access="hasRole('ROLE_USER')" 代表拥有的角色 代表用户权限  ROLE_前缀-->
    <intercept-url pattern="/**" access="hasRole('ROLE_USER')"/>
    <!-- login-page="/login.html" 默认登录地址 
    default-target-url="/index.html" 登录成功后跳转的页面
    default-target-url="/index.html" always-use-default-target="true" 必须结合使用
    authentication-failure-url="/login_error.html" 登录失败跳转该页面
    -->
    <form-login login-page="/login.html" 
    default-target-url="/admin/index.html" 
    always-use-default-target="true" 
    authentication-failure-url="/login_error.html"  
   
    />
    <logout/>
   <!-- 关闭跨域攻击 -->
    <csrf disabled="true"/>
     <headers>
	<frame-options policy="SAMEORIGIN"/>
     </headers>

    <!--注销-->
    <logout/>
    
</http>
<!-- 配置认证管理器
   1.提供者
   2.提供者配置用户名 和密码
   authorities=""拥有的权限
 -->
<authentication-manager alias="authenticationManager">
    <authentication-provider user-service-ref="userDetailService">

        <password-encoder ref="bcryptEncoder"></password-encoder>
    </authentication-provider>
</authentication-manager>




    <!--dubbo配置-->
    <dubbo:application name="shop-manager-web" />
    <dubbo:registry address="zookeeper://192.168.100.101:2181"/>
    <dubbo:reference id="sellerService"
                     interface="com.zym.sellersgood.service.SellerService" >
    </dubbo:reference>
    
    <!--实例化你的自定义认证类-->
    <bean:bean id="userDetailService"
               class="com.zym.shop.service.UserDetailsServiceImpl">
        <bean:property name="sellerService" ref="sellerService"></bean:property>

    </bean:bean>

    <!--加密算法-->
    <bean:bean id="bcryptEncoder"
               class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" />
</bean:beans>



springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <property name="supportedMediaTypes" value="application/json"/>
                <property name="features">
                    <array>
                        <value>WriteMapNullValue</value>
                        <value>WriteDateUseDateFormat</value>
                    </array>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
    <!-- 引用dubbo 服务 -->
    <!--<dubbo:application name="shop-web" />-->
    <!--<dubbo:registry address="zookeeper://192.168.100.101:2181"/>-->
    <!--<dubbo:annotation package="com.zym.shop.controller" />-->
    <!--<dubbo:reference timeout="4000" retries="0" interface="com.zym.sellersgood.service.BrandService" id="BrandService" registry="globalRegistry"/>-->
    <dubbo:annotation package="com.zym.shop.controller" />
</beans>

使用Security

前端
需要post方法,action=login

<form class="sui-form" action="/login" method="post" id="formlogin">

	<div class="logined">
		<a class="sui-btn btn-block btn-xlarge btn-danger" onclick="document:formlogin.submit()"target="_blank">&nbsp;&nbsp;</a>
	</div>
</form>

显示用户名

js文件

indexController.js

app2.controller("indexController",function ($scope,$controller,loginService) {
    $controller('baseController',{$scope:$scope});

    $scope.getUserName=function () {

        loginService.getName().success(function (response) {
          
            $scope.name=response.loginName;
        })
    }

})

后端代码

loginController.java

package com.zym.shop.controller;


import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/login")
public class LoginController {


    @RequestMapping("/name")
       public Map name(){
        String name = SecurityContextHolder.getContext().getAuthentication().getName();
        Map map = new HashMap<>();
        map.put("loginName",name);
        return map;

    }


}


密码加密(BCrypt 加密算法)

用户表的密码通常使用 MD5 等不可逆算法加密后存储,为防止彩虹表破解更会先使用
一个特定的字符串(如域名)加密,然后再使用一个随机的 salt(盐值)加密。 特定字符
串是程序代码中固定的,salt 是每个密码单独随机,一般给用户表加一个字段单独存储,比
较麻烦。 BCrypt 算法将 salt 随机并混入最终加密后的密码,验证时也无需单独提供之前的
salt,从而无需单独处理 salt 问题。

后端代码

/**

* 增加

* @param seller

* @return

*/

@RequestMapping("/add")

public Result add(@RequestBody TbSeller seller){

//密码加密

BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

String password = passwordEncoder.encode(seller.getPassword());

seller.setPassword(password);

try {

sellerService.add(seller);

return new Result(true, "增加成功");

} catch (Exception e) {

e.printStackTrace();

return new Result(false, "增加失败");

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值