SpringSecurity(3)

认证后用户信息获取

//获取当前用户信息
    private String getUsername(){
        String username = null;
        //当前认证通过的用户身份
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //用户身份
        Object principal = authentication.getPrincipal();
        if(principal == null){
            username = "匿名";
        }
        if(principal instanceof org.springframework.security.core.userdetails.UserDetails){
            UserDetails userDetails = (UserDetails) principal;
            username = userDetails.getUsername();
        }else{
            username = principal.toString();
        }
        return username;
    }

授权

  • 通过 url拦截进行授权
authenticated() 保护URL,需要用户登录 
permitAll() 指定URL无需保护,一般应用与静态资源文件 
hasRole(String role) 限制单个角色访问,角色将被增加 “ROLE_” .所以”ADMIN” 
		将和 “ROLE_ADMIN”进行比较. 
hasAuthority(String authority) 限制单个权限访问 
hasAnyRole(String… roles)允许多个角色访问. 
hasAnyAuthority(String… authorities) 允许多个权限访问. 
access(String attribute) 该方法使用 SpEL表达式, 所以可以创建复杂的限制.
hasIpAddress(String ipaddressExpression) 限制IP地址或子网
  • 通过 方法拦截进行授权
1: @EnableGlobalMethodSecurity(securedEnabled = true) 注解开启
2@Secured("ROLE_TELLER")
3@PreAuthorize
4@PostAuthorize

分布式系统认证方案

  • 流程

在这里插入图片描述

Spring Cloud Security OAuth2

  • 图解
    在这里插入图片描述
授权服务 uaa
客户端进行认证,返回token信息
public class AuthorizationServerConfigurerAdapter implements AuthorizationServerConfigurer {
    public AuthorizationServerConfigurerAdapter() {
    }

    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
    }

    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    }

    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
    }
}

  • ClientDetailsServiceConfigurer
用来配置客户端详情服务(ClientDetailsService),客户端详情信息在 这里进行初始化,
你能够把客户端详情信息写死在这里或者是通过数据库来存储调取详情信息

默认实现从 oauth_client_details 表中获取客户端信息
  • AuthorizationServerEndpointsConfigurer
用来配置令牌(token)的访问端点和令牌服务(token services)

令牌管理包括:
令牌可否刷新
令牌有效期
令牌存储策略

/oauth/authorize:授权端点。 
/oauth/token:令牌端点。 
/oauth/confirm_access:用户确认授权提交端点。 
/oauth/error:授权服务错误信息端点。 
/oauth/check_token:用于资源服务访问的令牌解析端点。 
/oauth/token_key:提供公有密匙的端点,如果你使用JWT令牌的话。
  • AuthorizationServerSecurityConfigurer
用来配置令牌端点的安全约束
资源服务
校验token 返回资源

授权模式

  • 授权码模式
    在这里插入图片描述
  • 简化模式
    在这里插入图片描述
  • .密码模式
    在这里插入图片描述
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值