简单使用下spring的security
使用包括以下三个部分:
1.springSecurity本身的配置文件(当然这里可以改为配置类,目前我使用的是配置文件;配置需要拦截的url以及用户需要哪些权限才能访问,配置认证管理器,注入自定义认证类等)
2.自定义认证类(实现用户的认证和授权,编码者自己书写业务流程)
3.密码加密类(用户密码加密使用的类,在登录和注册的时候都需要使用)
下面给出具体的使用:只给出关键文件
1.spring-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.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
<!--配置不拦截的url-->
<http pattern="/*.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 pattern="/seller/add.do" security="none"></http>
<!--配置拦截的url-->
<http use-expressions="false">
<intercept-url pattern="/**" access="ROLE_SELLER"/>
<!--配置登录页 登录失败和 登录成功后跳转的页面-->
<form-login login-page="/shoplogin.html" default-target-url="/admin/index.html"
authentication-failure-url="/shoplogin.html" always-use-default-target="true"/>
<csrf disabled="true"></csrf>
<!--显示内置框架-->
<headers>
<frame-options policy="SAMEORIGIN"></frame-options>
</headers>
<!--注销 成功后跳转的的url-->
<logout logout-success-url="/shoplogin.html"></logout>
</http>
<!--配置认证管理器-->
<authentication-manager>
<!--配置自定义认证类 这里可以直接配置授权用户-->
<authentication-provider user-service-ref="myUserDeatilsService">
<!--配置用户密码加密的类-->
<password-encoder ref="passwordEncoder"></password-encoder>
</authentication-provider>
</authentication-manager>
<!--注入自定义的认证类-->
<beans:bean id="myUserDeatilsService" class="com.pyg.shop.web.service.MyUserDeatilsService">
</beans:bean>
<!--注入用户密码使用的加密类 用户注册的时候 就用这个工具类进行加密-->
<beans:bean id="passwordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"></beans:bean>
</beans:beans>
2.自定义认证类:
package com.pyg.shop.web.service;
import com.common.constant.CommonConstant;
import com.pyg.pojo.Seller;
import com.pyg.sellergoods.api.ISellerService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
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 java.util.ArrayList;
import java.util.List;
/**
* @author lf
* @Description: 自定义认证类
* @date 2018/6/2017:37
*/
public class MyUserDeatilsService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//初始化spring 容器 从容器中获取服务 因为该类 不能由容器管理 所以 不能自动注入需要的服务
ApplicationContext cnt = new ClassPathXmlApplicationContext("classpath:config/*.xml");
ISellerService sellerService = (ISellerService) cnt.getBean("sellerService"); //dubbo服务中的类
System.out.println("springSecurity 自定义认证类");
//创建角色(权限)集合
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
authorities.add(new SimpleGrantedAuthority("ROLE_SELLER"));
//查询商家信息(从数据库中获取用户信息)
Seller seller = sellerService.findOne(username);
//判断商家是否可以登录
if(seller!=null && CommonConstant.REVIEWED_PASS.equals(seller.getStatus())){
//商家信息存在 并且 是通过审核状态 则可以登录
return new User(username,seller.getPassword(),authorities);//匹配用户信息和数据库中信息是否一致,并且授权authorities中的角色
}else{
return null;
}
}
}
3.给出用户注册的时候调用的后台类:
package com.pyg.shop.web.controller;
import com.common.vo.ResultInfo;
import com.pyg.pojo.Seller;
import com.pyg.sellergoods.api.ISellerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
/**
* @author lf
* @Description: 商家相关服务
* @date 2018/6/2014:15
*/
@RestController
@RequestMapping("/seller")
public class SellerController {
@Autowired
private ISellerService sellerService =null;
//增
@RequestMapping("/add")
private ResultInfo add(@RequestBody Seller seller){
//密码加密
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String password = passwordEncoder.encode(seller.getPassword());
seller.setPassword(password);
try {
sellerService.add(seller);
return new ResultInfo(true,"操作成功");
}catch (Exception ex){
return new ResultInfo(false,"操作失败");
}
}
//获取当前登录用户名
@RequestMapping("/getLoginUser")
public Map getLoginUser(){
String name = SecurityContextHolder.getContext().getAuthentication().getName();
Map res = new HashMap();
res.put("loginName",name);
return res;
}
}