单点登录(微服务)

  • 概念
    简称SSO,只需要一次登录就可以访问同一个服务器站点的所有服务
  • 实现基于用户id查找用户权限(系统基础服务)
    SQL语句
#单表查询
#基于用户id查询用户对应的角色id〔查询出的角色id可能是多个)
select role_id from tb_user_roles where user_id=1;
#基于角色id查询用户对应的菜单id
select menu_id from tb_role_menus where role_id in (1);
#基于菜单id查询菜单权限标识
select permission from tb_menus where id in (1,2,3);

#嵌套查询
select permission from tb_menus where id in (
    select menu_id from tb_role_menus where role_id in (
        select role_id from tb_user_roles where user_id=1));

#多表联查
select distinct m.permission
    from tb_user_roles ur,tb_role_menus rm,tb_menus m
        where ur.role_id=rm.role_id and rm.menu_id=m.id and ur.user_id=1;

Mapper接口:

@Mapper
public interface UserMapper extends BaseMapper<User> {

    @Select("select id,username,password,status " +
            "from tb_users " +
            "where username=#{username}")
    User selectUserByUsername(String username);
    /**
     * 基于用户id查询用户权限
     * 1- tb_user_roles(用户角色关系表,可以再此表中基于用户id找到用户角色)
     * 2- tb_role_menus(角色菜单关系表,可以基于角色id找到菜单id)
     * 3- tb_menus(菜单表,菜单为资源的外在表现形式,在此表中可以基于菜单id找到权限标识)
     * @param userId 用户id
     * @return 用户的权限
     * 涉及到的表:tb_user_roles,tb_role_menus,tb_menus
     */
    @Select("select distinct m.permission " +
            "from tb_user_roles ur,tb_role_menus rm,tb_menus m " +
            "where ur.role_id=rm.role_id and rm.menu_id=m.id " +
            "and ur.user_id=#{userId}")
    List<String> selectUserPermissions(Long userId);
}

Controller:

@RestController
@RequestMapping("/user/")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/login/{username}")
    public User doSelectUserByUsername(
            @PathVariable("username") String username){
        return userService.selectUserByUsername(username);
    }
    @GetMapping("/permission/{userId}")
    public List<String> doSelectUserPermissions(
            @PathVariable("userId") Long userId){
        return userService.selectUserPermissions(userId);
    }
}

ServiceImpl:

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public User selectUserByUsername(String username) {
        return userMapper.selectUserByUsername(username);
    }
    @Override
    //方案1∶在这里可以调用数据层的单表查询方法,查询三次获取用户信息
    //方案2∶在这里可以调用数据层的多表嵌套或多表关联方法执行1次查询
    public List<String> selectUserPermissions(Long userId) {
        return userMapper.selectUserPermissions(userId);
    }
}
  • 统一认证
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
         http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>02-sso</artifactId>
        <groupId>com.jt</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>sso-auth</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <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>
        <!--SSO技术方案:SpringSecurity+JWT+oauth2-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-oauth2</artifactId>
        </dependency>
        <!--open feign-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
    </dependencies>
</project>

RemoteUserService:

@FeignClient(value = "sso-system",contextId = "remoteUserService")
public interface RemoteUserService {
    @GetMapping("/user/login/{username}")
    User doSelectUserByUsername(@PathVariable("username") String username);
    @GetMapping("/user/permission/{userId}")
    List<String> doSelectUserPermissions(@PathVariable("userId") Long userId);
}

认证管理器UserServiceDetail:
1.基于用户名查找用户信息,判定用户是否存在
2.基于用户id查询用户权限(登录用户不一定可以访问所有资源
3.封装查询结果并返回.

/**
 * 在此对象中实现远程服务调用,从sso-system服务中获取用户信息,
 * 并对用户信息进行封装返回,交给认证管理器(AuthenticationManager)去完成密码的比对操作.
 */
@Service
@Slf4j
public class UserServiceDetail implements UserDetailsService {
    @Autowired
    private RemoteUserService remoteUserService;
    //执行登录操作时,提交登录按钮系统会调用此方法
    /**
     * @param
     * @return 登录用户信息和用户权限信息,返回值最终会交给认证管理器
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException {
        //1.基于用户名获取用户信息
        com.jt.auth.pojo.User remoteuser=
                remoteUserService.doSelectUserByUsername(username);
        if(remoteuser==null)
            throw new UsernameNotFoundException("用户不存在");
        //2.基于用于id查询用户权限
        final List<String> permissions=
                remoteUserService.doSelectUserPermissions(remoteuser.getId());
        log.info("permissions {}",permissions);
        //3.对查询结果进行封装并返回
        return new User(username,
                remoteuser.getPassword(),
                AuthorityUtils.createAuthorityList(permissions.toArray(new String[]{})));
        //返回给认证中心,认证中心会基于用户输入的密码以及数据库的密码做一个比对
    }
}

处理登录Security配置类

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.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
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 {
    //构建密码加密对象,登录时系统会基于此对象进行密码加密
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    /**
     * 定义认证管理器对象,这个对象负责完成用户信息的认证,
     * 即判定用户身份信息的合法性,在基于oauth2协议完成认
     * 证时,需要此对象,所以这里讲此对象拿出来交给spring管理
     */
    @Bean
    public AuthenticationManager authenticationManagerBean()
            throws Exception {
        return super.authenticationManager();
    }

    /**配置认证规则*/
    @Override
    protected void configure(HttpSecurity http)
            throws Exception {
        //super.configure(http);//默认所有请求都要认证
        //1.禁用跨域攻击(先这么写,不写会报403异常)
        http.csrf().disable();
        //2.放行所有资源的访问(后续可以基于选择对资源进行认证和放行)
        http.authorizeRequests()
                .anyRequest().permitAll();
        //3.自定义定义登录成功和失败以后的处理逻辑(可选)
        //假如没有如下设置登录成功会显示404
        http.formLogin()//这句话会对外暴露一个登录路径/login
                .successHandler(successHandler())
                .failureHandler(failureHandler());
    }
    //定义认证成功处理器
    //登录成功以后返回json数据
    @Bean
    public AuthenticationSuccessHandler successHandler(){
        //lambda
        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();
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值