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 { 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 { @GetMapping("/user/login/{username}") User selectUserByUsername(@PathVariable("username") String username); // 基于用户id获取权限 @GetMapping("/user/permission/{userId}") ListselectUserPermissions(@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方法,相当于定义一个规范,作用主要是用来和数据库做交互用的。
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 { //调用我们之前接口写的调用远程服务的方法 @Autowired private RemoteUserService remoteUserService; @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定义Security类配置permissions= remoteUserService.selectUserPermissions(user.getId()); log.info("permissions {}",permissions); //3.对查询结果进行封装并返回 // List authorityList = AuthorityUtils.createAuthorityList(permissions.toArray(new String[]{})); User userInfo= new User(username, user.getPassword(), AuthorityUtils.createAuthorityList(permissions.toArray(new String[]{}))); //数据库里的密码是已加密的,用户提交的是未加密的,这样要比对密码。需要配置一个算法 return userInfo; //返回给认证中心,认证中心会基于用户输入的密码以及数据库的密码做一个比对 } }
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());
然后再写自定义的登录成功信息和失败信息。
401异常:没有认证 403异常:没有权限//定义认证成功处理器
//登录成功以后返回json数据
@Bean
public AuthenticationSuccessHandler successHandler(){
//lambda---jdk8特殊写法
return (request,response,authentication)->{
//构建map对象封装到要响应到客户端的数据
Mapmap=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对象封装到要响应到客户端的数据
Mapmap=new HashMap<>();
map.put("state",500);
map.put("message", "login error");
//将map对象转换为json格式字符串并写到客户端
writeJsonToClient(response,map);
};
}
private void writeJsonToClient(
HttpServletResponse response,
Mapmap) 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();
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)