流程:认证服务sso-auth--->openFeign -->系统服务(sso-system)
1、sso-auth:第一步要提供一个user封装的类,用来接收数据库查询到的数据。
package com.jt.auth.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import org.springframework.security.core.GrantedAuthority;
import java.io.Serializable;
import java.util.List;
@Data
@Accessors(chain = true)
@NoArgsConstructor
@AllArgsConstructor
public class User implements Serializable {
/**
* 封装user对象,基于此对象用来接收远程服务获取到的用户信息
* 流程:
* 通过feign方式调用远程服务
* 认证服务sso-auth--->openFeign -->系统服务(sso-system)
*
*/
private static final long serialVersionUID = -6488621916389199077L;
private Long id;
private String username;
private String password;
private String status;
}
2、要调用sso-system里的查询数据库的方法,需要使用feign调用,这里就需要提供一
个 openFeign接口(也就是定义一个远程service对象),来进行调用sso-system类中的方法。
需要在启动类中使用@EnableFeignClients,还有在调用方法的接口中使用@FeignClient这两个注解来实现远程服务调用
package com.jt.auth.service;
import com.jt.auth.pojo.User;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import java.util.List;
@FeignClient(value = "sso-system",contextId = "remoteUserService")
public interface RemoteUserService {
/**
* 基于这个接口进行sso-system服务调用
*
* 基于用户名获取用户信息
* @param username
* @return
*/
@GetMapping("/user/login/{username}")
User selectUserByUsername(@PathVariable("username") String username);
// 基于用户id获取权限
@GetMapping("/user/permission/{userId}")
List<String> selectUserPermissions(@PathVariable("userId") Long userId);
}
3、定义一个service实现类来处理业务对象,实现类是实现spring-security框架提供的认证管理器接口,---UserDetailsService接口。
先将接口封装调用的远程服务方法通过@Autowired注入进去,通过重写UserDetailsService接口里的loadUserByUsername方法,对基于feign方式的调用得到的用户参数进行数据封装到user中。
在通过user属性中的id,获取对应的权限方法获取权限信息。再将查询到信息封装并返回去。
返回给认证中心,认证中心会基于用户输入的密码以及数据库的密码做一个比对
这里查询到的数据封装的user对象,使用的是springorg.springframework.security.core.userdetails提供的user对象
AuthorityUtils这个工具去转换查询到的权限属性。
并且数据返回到认证中心后,认证中心会将用户输入的信息,与数据库中的信息进行对比,由于数据库中的登录密码是加密的,一般数据库中的加密是不可逆的。所以我们会加一个加密方法对用户提交的密码先加密,再与数据库中的密码进行对比。
// 构建加密算法,基于此算法对用户提交的密码进行加密
@Bean
public BCryptPasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
在这里要介绍一下UserDetailsService 接口:
userDetails是spring-security基础接口,包含某个账号,密码,权限,状态(是否锁定)等信息,只有getter方法,相当于定义一个规范,作用主要是用来和数据库做交互用的。
作用:
Spring Security中进行身份验证的是AuthenticationManager接口,ProviderManager是它的一个默认实现,但它并不用来处理身份认证,而是委托给配置好的AuthenticationProvider,每个AuthenticationProvider会轮流检查身份认证。检查后或者返回Authentication对象或者抛出异常。
验证身份就是加载响应的UserDetails,看看是否和用户输入的账号、密码、权限等信息匹配。此步骤由实现AuthenticationProvider的DaoAuthenticationProvider(它利用UserDetailsService验证用户名、密码和授权)处理。包含 GrantedAuthority 的 UserDetails对象在构建 Authentication对象时填入数据。
AuthorityUtils:
此类一般用于UserDetailsService的实现类中的loadUserByUsername方法
此工具一共有三个方法:
1、createAuthorityList:将权限转化为list,一个权限一个参数。
2、commaSeparatedStringToAuthorityList:作用为给user的账户添加一个或多个权限,用逗号分隔,底层调用的是createAuthorityList方法,唯一的区别在于此方法把所有权限包含进一个字符串参数中,只是用逗号分隔。
3、authorityListToSet:将GrantedAuthority对象的数据转换成set。
package com.jt.auth.service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
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 org.springframework.stereotype.Service;
import java.util.List;
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
/**
* 自定义用户执行登录操作逻辑(系统默认用户为user,密码是控制台密码-随机字符串)
* client-->username ,password
* server-->未加密的密码进行加密,与数据库已加密的密码进行比对
*
* 调用远程服务的接口---RemoteUserService
* UserDetailsService:认证管理器
* loadUserByUsername:---基于用户名查询权限的方法
* 认证流程:spring-security----这个执行链底层框架已经设计好了,我们只需要提供UserDetailsServiceImpl对象获取远端服务或者数据库中的用户信息
* 1、客户端提交用户名和密码
* 2、服务端调用spring-security框架启动过滤器Filters,对用户名和密码进行预处理
* 3、过滤器(Filters)会调用认证管理器(AuthenticationManager),完成认证。也就是比对用户名和密码
* 4、认证管理器会调用UserDetailsServiceImpl对象获取远端服务或者数据库中的用户信息,然后与客户端提交的信息进行比对
*/
//调用我们之前接口写的调用远程服务的方法
@Autowired
private RemoteUserService remoteUserService;
/**
* 基于用户名获取数据库中的用户信息
* @param username 这个username来自客户端
* @return
* @throws UsernameNotFoundException
*/
@Override
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
//基于feign方式获取远程数据并封装
//1.基于用户名获取用户信息
com.jt.auth.pojo.User user= remoteUserService.selectUserByUsername(username);
if(user==null)
throw new UsernameNotFoundException("用户不存在");
//2.基于用于id查询用户权限
List<String> permissions= remoteUserService.selectUserPermissions(user.getId());
log.info("permissions {}",permissions);
//3.对查询结果进行封装并返回
// List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList(permissions.toArray(new String[]{}));
User userInfo= new User(username, user.getPassword(), AuthorityUtils.createAuthorityList(permissions.toArray(new String[]{})));
//数据库里的密码是已加密的,用户提交的是未加密的,这样要比对密码。需要配置一个算法
return userInfo;
//返回给认证中心,认证中心会基于用户输入的密码以及数据库的密码做一个比对
}
}
定义Security类配置
1、可以将启动类中的加密算法,转移到配置类中。
// 构建加密算法,基于此算法对用户提交的密码进行加密
@Bean
public BCryptPasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
2、WebSecurityConfigurerAdapter实现了WebSecurityConfigurer接口。作为一个适配器,为程序想重写那个方法作为提供类,这样不用去重写接口里的所有方法。
3、AuthenticationManager (认证管理器),定义认证管理器对象,这个对象负责完成用户信息的认证, 即判定用户身份信息的合法性,在基于oauth2协议完成认 证时,需要此对象,所以这里讲此对象拿出来交给spring管理
@Bean
public AuthenticationManager authenticationManagerBean()
throws Exception {
return super.authenticationManager();
}
4、这个配置类是继承WebSecurityConfigurerAdapter这个适配器类,重写的是configure方法,里面要设置
1)、关闭跨域攻击:http.csrf().disable();----假如没有关闭跨域攻击,使用postman,idea里的httpclient,这些工具去访问路径的时候,请求会报403异常---权限认证异常
2)、设置请求认证规则(系统默认规则是所有资源必须先认证才能访问)
http.authorizeRequests().anyRequest().authenticated();---系统默认
当我们需要设置那些资源需要认证再访问,那些资源不需要认证可以直接访问
http.authorizeRequests().mvcMatchers("页面路径").authenticated()---这个是设置需要先认证才能访问。
也可以链式写:
http.authorizeRequests().mvcMatchers("页面路径").authenticated().anyRequest().permitAll();---只设置括号里的页面路径需要先认证,其余的都放行
3)、可以自定义定义登录成功和失败以后的处理逻辑。---设置认证结果处理器--http.formLogin();这个认证成功后会跳转到index.html页面。后面也可以加.successHandler(successHandler()) .failureHandler(failureHandler());来自定义登录成功或失败的处理信息。
http.formLogin().successHandler(successHandler()) .failureHandler(failureHandler());
然后再写自定义的登录成功信息和失败信息。
//定义认证成功处理器
//登录成功以后返回json数据
@Bean
public AuthenticationSuccessHandler successHandler(){
//lambda---jdk8特殊写法
return (request,response,authentication)->{
//构建map对象封装到要响应到客户端的数据
Map<String,Object> map=new HashMap<>();
map.put("state",200);
map.put("message", "login ok");
//将map对象转换为json格式字符串并写到客户端
writeJsonToClient(response,map);
};
}
//定义登录失败处理器
@Bean
public AuthenticationFailureHandler failureHandler(){
return (request,response,exception)->{
//构建map对象封装到要响应到客户端的数据
Map<String,Object> map=new HashMap<>();
map.put("state",500);
map.put("message", "login error");
//将map对象转换为json格式字符串并写到客户端
writeJsonToClient(response,map);
};
}
private void writeJsonToClient(
HttpServletResponse response,
Map<String,Object> map) throws IOException {
//将map对象,转换为json
String json=new ObjectMapper().writeValueAsString(map);
//设置响应数据的编码方式
response.setCharacterEncoding("utf-8");
//设置响应数据的类型
response.setContentType("application/json;charset=utf-8");
//将数据响应到客户端
PrintWriter out=response.getWriter();
out.println(json);
out.flush();
}