All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.dennisit.vplus.data.security.OAuth2Realm Maven / Gradle / Ivy

package com.github.dennisit.vplus.data.security;

import com.github.dennisit.vplus.data.enums.common.EnableEnum;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import java.util.Optional;

/**
 * Created by hh on 2017/11/18.
 */
public class OAuth2Realm extends AuthorizingRealm {

    private OAuth2IFace oAuth2IFace;

    public OAuth2Realm(OAuth2IFace oAuth2IFace){
        this.oAuth2IFace = oAuth2IFace;
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof OAuth2Token;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        OAuth2 oAuth2 = (OAuth2)principal.getPrimaryPrincipal();
        long userId = oAuth2.getUserId();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.addStringPermissions(oAuth2IFace.selectPermissions(userId));
        authorizationInfo.addRoles(oAuth2IFace.selectRoles(userId));
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authentication) throws AuthenticationException {
        String token = (String) authentication.getPrincipal();

        // 查询Token
        OAuth2 oAuth2 =  oAuth2IFace.selectByToken(token);
        if(null ==  oAuth2 || Optional.ofNullable(oAuth2.getExpireTime()).map(x -> x.getTime()).orElse(0L) < System.currentTimeMillis()){
            throw new IncorrectCredentialsException("token失效,请重新登录.");
        }

        //查询用户信息
        oAuth2 = oAuth2IFace.selectByUserId(oAuth2.getUserId());
        if(null == oAuth2){
            throw new UnknownAccountException("账号不存在.");
        }
        if(EnableEnum.DISABLE.getValue() == oAuth2.getEnabled()){
            throw new LockedAccountException("账号被锁定.");
        }

        return new SimpleAuthenticationInfo(oAuth2, token, getName());
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy