多点登陆系统。应用起来相对繁琐(每次访问资源服务都需要重新登陆认证和授权)。与此同时,系统代码的重复也比较高。所以单点登录系统,倍受欢迎!
单点登录系统,即多个站点共用一台认证授权服务器,用户在其中任何一个站点登录后,可以免登录访问其他所有站点。而且,各站点间可以通过该登录状态直接交互。
在文件上传的项目添加认证授权服务,义登录页面(login.html),然后在页面中输入自己的登陆账号,登陆密码,将请求提交给网关,然后网关将请求转发到auth工程,登陆成功和失败要返回json数据,按照如下结构实现
在02-sca工程创建 sca-auth子module,作为认证授权服务
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
在sca-auth工程中创建bootstrap.yml文件
server:
port: 8071
spring:
application:
name: sca-auth
cloud:
nacos:
discovery:
server-addr: localhost:8848
config:
server-addr: localhost:8848
package com.jt;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ResourceAuthApplication {
public static void main(String[] args) {
SpringApplication.run(ResourceAuthApplication.class, args);
}
}
项目启动时,系统会默认生成一个登陆密码
打开浏览器输入http://localhost:8071呈现登陆页面
默认用户名为user,密码为系统启动时,在控制台呈现的密码。执行登陆测试,登陆成功进入如下界面(因为没有定义登陆页面,所以会出现404)
修改SecurityConfig配置类,添加登录成功或失败的处理逻辑
package com.jt.auth.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
@Configuration//配置对象--系统启动时底层会产生代理对象,来初始化一些对象
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//WebSecurityConfigurerAdapter 类是个适配器, 在配置的时候,需要我们自己写个配置类去继承他,然后编写自己所特殊需要的配置
//BCryptPasswordEncoder密码加密对象比MD5安全性更高,MD5暴力反射可以破解过
@Bean
public BCryptPasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
/**
* 配置认证管理器(负责对客户输入的用户信息进行认证),在其他配置类中会用到这个对象
* @return
* @throws Exception
*/
@Bean
public AuthenticationManager authenticationManagerBean()
throws Exception {
return super.authenticationManagerBean();
}
/**在这个方法中定义登录规则
* 1)对所有请求放行(当前工程只做认证)
* 2)登录成功信息的返回
* 3)登录失败信息的返回
* */
@Override
protected void configure(HttpSecurity http) throws Exception {
//禁用跨域
http.csrf().disable();
//放行所有请求
http.authorizeRequests().anyRequest().permitAll();
//登录成功与失败的处理
http.formLogin()
.successHandler(successHandler()) // .successHandler(AuthenticationSuccessHandler对象)
.failureHandler(failureHandler());
}
@Bean
//构建successHandler()方法来创建AuthenticationSuccessHandler对象
public AuthenticationSuccessHandler successHandler(){
// return new AuthenticationSuccessHandler() {
// @Override
// public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
//
// }
// }
return (request,response,authentication) ->{
//1.构建map对象,封装响应数据
Map<String,Object> map=new HashMap<>();
map.put("state",200);
map.put("message","login ok"); //登录成功返回的响应信息
//2.将map对象写到客户端
writeJsonToClient(response,map);
};
}
@Bean
//failureHandler();方法来创建AuthenticationSuccessHandler对象
public AuthenticationFailureHandler failureHandler(){
return (request,response, e)-> {
//1.构建map对象,封装响应数据
Map<String,Object> map=new HashMap<>();
map.put("state",500);
map.put("message","login failure");//登录失败返回的响应信息
//2.将map对象写到客户端
writeJsonToClient(response,map);
};
}
//提取公共代码,将对象转为Json传给客户端, 构建writeJsonToClient();
private void writeJsonToClient(HttpServletResponse response,
Object object) throws IOException {
// Object 类型,不只是Map类型,说不准
//2.将对象转换为json
//Gson-->toJson (需要自己找依赖)
//fastjson-->JSON (spring-cloud-starter-alibaba-sentinel)
//jackson-->writeValueAsString (spring-boot-starter-web)
String jsonStr=new ObjectMapper().writeValueAsString(object);
//3.将json字符串写到客户端
PrintWriter writer = response.getWriter();
writer.println(jsonStr);
writer.flush();
}
}
正常来说,用来与数据库中的用户信息作对比,认证是否正确,可否授权
package com.jt.auth.service;
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.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 登录时用户信息的获取和封装会在此对象进行实现,
* 在页面上点击登录按钮时,会调用这个对象的loadUserByUsername方法,
* 页面上输入的用户名会传给这个方法的参数
*
*/
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
//获取用户详细信息的接口
@Autowired
//BCryptPasswordEncoder密码加密对象
private BCryptPasswordEncoder passwordEncoder;
//UserDetails用户封装用户信息(认证和权限信息)
@Override
//重写UserDetailsService 接口中的 loadUserByUsername();方法,定义用来核对数据库数据和授于相应的权限
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
//1.基于用户名查询用户信息(用户名,用户状态,密码,....)
//Userinfo userinfo=userMapper.selectUserByUsername(username);数据库用户信息查询操作简写了
String encodedPassword=passwordEncoder.encode("123456");
//2.查询用户权限信息(后面访问数据库)
//这里先给几个假数据
List<GrantedAuthority> authorities =
AuthorityUtils.createAuthorityList(//这里的权限信息先这么写,后面讲
"sys:res:create", "sys:res:retrieve");
//3.对用户信息进行封装
return new User(username,encodedPassword,authorities);
}
}
在网关配置文件中添加如下配置
server:
port: 9001
spring:
application:
name: sca-resource-gateway
cloud:
sentinel: #限流设计
transport:
dashboard: localhost:8180
eager: true
nacos:
discovery:
server-addr: localhost:8848
config:
server-addr: localhost:8848
file-extension: yml
gateway:
discovery:
locator:
enabled: true
routes:
- id: router02
uri: lb://sca-auth #lb表示负载均衡,底层默认使用ribbon实现
predicates: #定义请求规则(请求需要按照此规则设计)
- Path=/auth/login/** #请求路径设计,单体架构
filters:
- StripPrefix=1 #转发之前去掉path中第一层路径
启动sca-gateway,sca-auth服务,然后基于postman进行访问测试
在sca-resource-ui工程的static目录中定义login-sso.html 登陆页面