java类org.springframework.security.authentication.InsufficientAuthenticationException的实例源码

MainAccessDecisionManager.java 文件源码 项目:Fetax-AI 阅读 30 收藏 0 点赞 0 评论 0
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes)
        throws AccessDeniedException, InsufficientAuthenticationException {
    //System.err.println(" ---------------MaxAccessDecisionManager decide--------------- ");
    if(configAttributes == null) {
        return;
    }
    //所请求的资源拥有的权限(一个资源对多个权限)
    Iterator<ConfigAttribute> iterator = configAttributes.iterator();
    while(iterator.hasNext()) {
        ConfigAttribute configAttribute = iterator.next();
        //访问所请求资源所需要的权限
        String needPermission = configAttribute.getAttribute();
        //System.out.println("NEED-> "+needPermission);
        //用户所拥有的权限authentication
        for(GrantedAuthority ga : authentication.getAuthorities()) {
            //System.out.println("USER-> "+ga.getAuthority());
            if(needPermission.equals(ga.getAuthority())) {
                //System.out.println("pass");
                return;
            }
        }
    }
    //没有权限
    throw new AccessDeniedException("Access Denide!");
}
OwnAccessDecisionManager.java 文件源码 项目:data-migration 阅读 23 收藏 0 点赞 0 评论 0
@Override
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
    if(null== configAttributes || configAttributes.size() <=0) {
        return;
    }
    ConfigAttribute c;
    String needRole;
    for(Iterator<ConfigAttribute> iter = configAttributes.iterator(); iter.hasNext(); ) {
        c = iter.next();
        needRole = c.getAttribute();
        for(GrantedAuthority ga : authentication.getAuthorities()) {
            if(needRole.trim().equals(ga.getAuthority())) {
                return;
            }
        }
    }
    throw new AccessDeniedException("no right");
}
CustomerAccessDecisionManager.java 文件源码 项目:busi-support 阅读 30 收藏 0 点赞 0 评论 0
@Override
public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection)
        throws AccessDeniedException, InsufficientAuthenticationException {
    if (collection == null) {
        return;
    }
    String needRole;
    //遍历需要的角色,如果一样,则通过
    CustomerUserDetail userDetail = (CustomerUserDetail) authentication.getPrincipal();
    List<Role> userRoleList = securityService.getUserRoleList(userDetail.getUsername(), userDetail.getAccountType());
    for (ConfigAttribute configAttribute : collection) {
        needRole = configAttribute.getAttribute();
        for (Role role : userRoleList) {
            if (needRole.equals(role.getRoleCode())) {
                return;
            }
        }
    }
    throw new AccessDeniedException("Cannot Access!");
}
UserController.java 文件源码 项目:esup-ecandidat 阅读 29 收藏 0 点赞 0 评论 0
/**
 * @param viewClass
 * @return true si l'utilisateur peut accéder à la vue
 */
public boolean canCurrentUserAccessView(Class<? extends View> viewClass, Authentication auth) {
    if (auth == null) {
        return false;
    }
    MethodInvocation methodInvocation = MethodInvocationUtils.createFromClass(viewClass, "enter");
    Collection<ConfigAttribute> configAttributes = methodSecurityInterceptor.obtainSecurityMetadataSource()
            .getAttributes(methodInvocation);
    /* Renvoie true si la vue n'est pas sécurisée */
    if (configAttributes.isEmpty()) {
        return true;
    }
    /* Vérifie que l'utilisateur a les droits requis */
    try {
        methodSecurityInterceptor.getAccessDecisionManager().decide(auth, methodInvocation, configAttributes);
    } catch (InsufficientAuthenticationException | AccessDeniedException e) {
        return false;
    }
    return true;
}
MyAccessDecisionManager.java 文件源码 项目:itweet-boot 阅读 26 收藏 0 点赞 0 评论 0
@Override
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {

    if(null== configAttributes || configAttributes.size() <=0) {
        return;
    }
    ConfigAttribute c;
    String needRole;
    for(Iterator<ConfigAttribute> iter = configAttributes.iterator(); iter.hasNext(); ) {
        c = iter.next();
        needRole = c.getAttribute();
        for(GrantedAuthority ga : authentication.getAuthorities()) {
            if(needRole.trim().equals(ga.getAuthority())) {
                return;
            }
        }
    }
    throw new AccessDeniedException("no right");
}
CustomerAccessDecisionManager.java 文件源码 项目:springbootWeb 阅读 29 收藏 0 点赞 0 评论 0
@Override
public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection)
        throws AccessDeniedException, InsufficientAuthenticationException {
    if (collection == null) {
        return;
    }
    String needRole;
    //遍历需要的角色,如果一样,则通过,避免角色信息变了,从数据库取
    CustomerUserDetail userDetail = (CustomerUserDetail) authentication.getPrincipal();
    List<Role> roleList = securityService.getUserRoleList(userDetail.getUsername(), userDetail.getAccountType());
    for (ConfigAttribute configAttribute : collection) {
        needRole = configAttribute.getAttribute();
        for (Role aRoleList : roleList) {
            if (aRoleList != null && needRole.equals(aRoleList.getRoleCode())) {
                return;
            }
        }
    }
    throw new AccessDeniedException("Cannot Access!");
}
DemoAccessDecisionManager.java 文件源码 项目:SpringBootStudy 阅读 26 收藏 0 点赞 0 评论 0
@Override
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
    if (configAttributes == null) {
        return;
    }

    for (ConfigAttribute ca : configAttributes) {
        String needRole = ca.getAttribute();
        //ga 为用户所被赋予的权限。 needRole 为访问相应的资源应该具有的权限。
        for (GrantedAuthority ga : authentication.getAuthorities()) {
            if (needRole.trim().equals(ga.getAuthority().trim())) {
                return;
            }
        }
    }

    throw new AccessDeniedException("没有权限进行操作!");
}
AjaxAuthenticationProvider.java 文件源码 项目:infotaf 阅读 29 收藏 0 点赞 0 评论 0
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    Assert.notNull(authentication, "No authentication data provided");

    String username = (String) authentication.getPrincipal();
    String password = (String) authentication.getCredentials();

    User user = userService.getByUsername(username).orElseThrow(() -> new UsernameNotFoundException("User not found: " + username));

    if (!encoder.matches(password, user.getPassword())) {
        throw new BadCredentialsException("Authentication Failed. Username or Password not valid.");
    }

    if (user.getRoles() == null) throw new InsufficientAuthenticationException("User has no roles assigned");

    List<GrantedAuthority> authorities = user.getRoles().stream()
            .map(authority -> new SimpleGrantedAuthority(authority.getRole().authority()))
            .collect(Collectors.toList());

    UserContext userContext = UserContext.create(user.getUsername(), authorities);

    return new UsernamePasswordAuthenticationToken(userContext, null, userContext.getAuthorities());
}
MainAccessDecisionManager.java 文件源码 项目:awe-awesomesky 阅读 29 收藏 0 点赞 0 评论 0
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes)
        throws AccessDeniedException, InsufficientAuthenticationException {
    //System.err.println(" ---------------MaxAccessDecisionManager decide--------------- ");
    if(configAttributes == null) {
        return;
    }
    //所请求的资源拥有的权限(一个资源对多个权限)
    Iterator<ConfigAttribute> iterator = configAttributes.iterator();
    while(iterator.hasNext()) {
        ConfigAttribute configAttribute = iterator.next();
        //访问所请求资源所需要的权限
        String needPermission = configAttribute.getAttribute();
        //System.out.println("NEED-> "+needPermission);
        //用户所拥有的权限authentication
        for(GrantedAuthority ga : authentication.getAuthorities()) {
            //System.out.println("USER-> "+ga.getAuthority());
            if(needPermission.equals(ga.getAuthority())) {
                //System.out.println("pass");
                return;
            }
        }
    }
    //没有权限
    throw new AccessDeniedException("Access Denide!");
}
UrlAccessDecisionManager.java 文件源码 项目:bdf2 阅读 28 收藏 0 点赞 0 评论 0
@SuppressWarnings("unchecked")
public void decide(Authentication authentication, Object object,Collection<ConfigAttribute> configAttributes)throws AccessDeniedException, InsufficientAuthenticationException {
    if((authentication.getPrincipal() instanceof IUser)){
        IUser loginUser=(IUser)authentication.getPrincipal();
        if(loginUser.isAdministrator())return;          
    }
    int result=10;
    for (AccessDecisionVoter<Object> voter : getDecisionVoters()) {
        result = voter.vote(authentication, object, configAttributes);
        if(result==AccessDecisionVoter.ACCESS_ABSTAIN){
            continue;
        }
        if(result==AccessDecisionVoter.ACCESS_DENIED){
            throw new AccessDeniedException("Access is denied");
        }
        if(result==AccessDecisionVoter.ACCESS_GRANTED){
            break;
        }
    }
    if(result==AccessDecisionVoter.ACCESS_ABSTAIN && configAttributes.size()>0){
        throw new AccessDeniedException("Access is denied");
    }
}
RefreshTokenAuthenticationProvider.java 文件源码 项目:iotplatform 阅读 29 收藏 0 点赞 0 评论 0
private SecurityUser authenticateByUserId(UserId userId) {
  User user = userService.findUserById(userId);
  if (user == null) {
    throw new UsernameNotFoundException("User not found by refresh token");
  }

  UserCredentials userCredentials = userService.findUserCredentialsByUserId(user.getId());
  if (userCredentials == null) {
    throw new UsernameNotFoundException("User credentials not found");
  }

  if (!userCredentials.isEnabled()) {
    throw new DisabledException("User is not active");
  }

  if (user.getAuthority() == null)
    throw new InsufficientAuthenticationException("User has no authority assigned");

  UserPrincipal userPrincipal = new UserPrincipal(UserPrincipal.Type.USER_NAME, user.getEmail());

  SecurityUser securityUser = new SecurityUser(user, userCredentials.isEnabled(), userPrincipal);

  return securityUser;
}
MyAccessDecisionManager.java 文件源码 项目:Shop 阅读 30 收藏 0 点赞 0 评论 0
@Override
public void decide(Authentication authentication, Object object,Collection<ConfigAttribute> configAttributes)

        throws AccessDeniedException, InsufficientAuthenticationException {

    if(configAttributes == null){
        return  ;
    }
    Iterator<ConfigAttribute> ite = configAttributes.iterator();
    while(ite.hasNext()){

        ConfigAttribute ca = ite.next();

        String needRole = ((SecurityConfig)ca).getAttribute();

        for(GrantedAuthority grantedAuthority : authentication.getAuthorities()){
            if(needRole.trim().equals(grantedAuthority.getAuthority().trim())){
                return;
            }
        }
    }
    //û��Ȩ�޷���
    throw new AccessDeniedException("û��Ȩ�޷��ʣ�");

}
JSONPayloadAuthenticationFilter.java 文件源码 项目:interview-preparation 阅读 27 收藏 0 点赞 0 评论 0
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException,
ServletException {

    if (!"POST".equalsIgnoreCase(request.getMethod())) {
        throw new InsufficientAuthenticationException("Invalid HTTP Method. it accepts only POST ");
    }

    if (!isContentTypeValid(request)) {
        throw new InsufficientAuthenticationException("Invalid content type. It accepts JSON only.");
    }

    final LoginRequest loginRequest = getLoginRequest(request);

    System.err.println("attemptAuthentication");
    final UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword());

    // Allow subclasses to set the "details" property
    // setDetails(request, authRequest);

    return getAuthenticationManager().authenticate(authRequest);
}
WebSecurityConfig.java 文件源码 项目:interview-preparation 阅读 30 收藏 0 点赞 0 评论 0
/**
 * Decide.
 *
 * @param authentication
 *            the authentication
 * @param object
 *            the object
 * @param configAttributes
 *            the configuration attributes
 * @throws AccessDeniedException
 *             the access denied exception
 * @throws InsufficientAuthenticationException
 *             the insufficient authentication exception
 */
@Override
public void decide(final Authentication authentication, final Object object, final Collection<ConfigAttribute> configAttributes)
        throws AccessDeniedException, InsufficientAuthenticationException {

    boolean allowAccess = false;

    for (final GrantedAuthority grantedAuthority : authentication.getAuthorities()) {

        for (final ConfigAttribute attribute : configAttributes) {
            allowAccess = attribute.getAttribute().equals(grantedAuthority.getAuthority());
            if (allowAccess) {
                break;// this loop
            }
        }

    }

    if (!allowAccess) {
        throw new AccessDeniedException("Access is denied");
    }
}
WebSecurityConfig.java 文件源码 项目:interview-preparation 阅读 33 收藏 0 点赞 0 评论 0
/**
 * Decide.
 *
 * @param authentication
 *            the authentication
 * @param object
 *            the object
 * @param configAttributes
 *            the configuration attributes
 * @throws AccessDeniedException
 *             the access denied exception
 * @throws InsufficientAuthenticationException
 *             the insufficient authentication exception
 */
@Override
public void decide(final Authentication authentication, final Object object, final Collection<ConfigAttribute> configAttributes)
        throws AccessDeniedException, InsufficientAuthenticationException {

    boolean allowAccess = false;

    for (final GrantedAuthority grantedAuthority : authentication.getAuthorities()) {

        for (final ConfigAttribute attribute : configAttributes) {
            allowAccess = attribute.getAttribute().equals(grantedAuthority.getAuthority());
            if (allowAccess) {
                break;// this loop
            }
        }

    }

    if (!allowAccess) {
        throw new AccessDeniedException("Access is denied");
    }
}
DefaultAccessDecisionManager.java 文件源码 项目:SpringSecurity 阅读 25 收藏 0 点赞 0 评论 0
/**
 * 自定义访问策略
 * 
 * @param authentication
 *            用户及用户权限信息
 * @param object
 * @param configAttributes
 *            访问资源需要的权限
 * @throws AccessDeniedException
 * @throws InsufficientAuthenticationException
 * @see org.springframework.security.access.AccessDecisionManager#decide(org.springframework.security.core.Authentication,
 *      java.lang.Object, java.util.Collection)
 */
public void decide(Authentication authentication, Object object,
        Collection<ConfigAttribute> configAttributes)
        throws AccessDeniedException, InsufficientAuthenticationException {
    SysUserVO user = (SysUserVO) authentication.getPrincipal();
    logger.info("访问资源的用户为" + user.getUsername());
    // 如果访问资源不需要任何权限则直接通过
    if (configAttributes == null) {
        return;
    }
    Iterator<ConfigAttribute> ite = configAttributes.iterator();
    // 遍历configAttributes看用户是否有访问资源的权限
    while (ite.hasNext()) {
        ConfigAttribute ca = ite.next();
        String needRole = ((SecurityConfig) ca).getAttribute();
        // ga 为用户所被赋予的权限。 needRole 为访问相应的资源应该具有的权限。
        for (GrantedAuthority ga : authentication.getAuthorities()) {
            if (needRole.trim().equals(ga.getAuthority().trim())) {
                return;
            }
        }
    }
    throw new AccessDeniedException("没有权限访问! ");
}
AspectSecurity.java 文件源码 项目:tgi-commons 阅读 25 收藏 0 点赞 0 评论 0
private void securityCheck(String signatureName, ProceedingJoinPoint pjp) throws Exception {
    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    final UserClass theUser = getUser(authentication);
    if (theUser != null) {
        Collection<? extends SecurityPolicy> rules = securityCache.retrieve(theUser, signatureName);
        if (!checkRules(pjp, theUser, rules)) {
            throw new InsufficientAuthenticationException(
                    "Access to method "
                      //      + AspectSecurityUtils.getSignatureString(pjp)
                            + " is not allowed!");
        }
    } else {
        if (!getChecker(defaultPolicy).check(pjp, null)) {
            throw new InsufficientAuthenticationException(
                    "Access to method "
                      //      + AspectSecurityUtils.getSignatureString(pjp)
                            + " is not allowed!");

        }
    }
}
CustomAccessDecisionManager.java 文件源码 项目:prometheus 阅读 30 收藏 0 点赞 0 评论 0
/**
 * 如果用户拥有访问权限,则直接return。如果没有访问权限,那么抛出AccessDeniedException异常
 * 这个异常会被spring security检测到,从而引导到403页面
 * @param authentication 当前用户
 * @param o
 * @param collection 当前用户所访问的资源需要的权限
 * @throws AccessDeniedException
 * @throws InsufficientAuthenticationException
 */
@Override
public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {

    if(collection == null || collection.isEmpty())//如果不需要角色权限
        return;

    //当前用户所拥有的权限
    Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();

    if(authentication.getName().equals("admin"))//超级管理员拥有所有权限
        return;

    //遍历,判断当前用户是否具有访问权限
    for(ConfigAttribute ca : collection){
        for (GrantedAuthority ga : authorities){
            if(ca.getAttribute().equals(ga.getAuthority()))
                return;
        }
    }

    throw new AccessDeniedException("没有访问权限!");
}
PreAuthTokenSourceTrustAuthenticationProviderTest.java 文件源码 项目:hawkbit 阅读 34 收藏 0 点赞 0 评论 0
@Test
@Description("Testing that the controllerId in the URI request match with the controllerId in the request header but the request are not coming from a trustful source.")
public void priniciapAndCredentialsAreTheSameButSourceIpRequestNotMatching() {
    final String remoteAddress = "192.168.1.1";
    final String principal = "controllerId";
    final String credentials = "controllerId";
    final PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal,
            Arrays.asList(credentials));
    token.setDetails(webAuthenticationDetailsMock);

    when(webAuthenticationDetailsMock.getRemoteAddress()).thenReturn(remoteAddress);

    // test, should throw authentication exception

    try {
        underTestWithSourceIpCheck.authenticate(token);
        fail("as source is not trusted.");
    } catch (final InsufficientAuthenticationException e) {

    }
}
PreAuthTokenSourceTrustAuthenticationProviderTest.java 文件源码 项目:hawkbit 阅读 28 收藏 0 点赞 0 评论 0
@Test(expected = InsufficientAuthenticationException.class)
public void principalAndCredentialsAreTheSameSourceIpListNotMatches() {
    final String[] trustedIPAddresses = new String[] { "192.168.1.1", "192.168.1.2", "192.168.1.3" };
    final String principal = "controllerId";
    final String credentials = "controllerId";
    final PreAuthenticatedAuthenticationToken token = new PreAuthenticatedAuthenticationToken(principal,
            Arrays.asList(credentials));
    token.setDetails(webAuthenticationDetailsMock);

    when(webAuthenticationDetailsMock.getRemoteAddress()).thenReturn(REQUEST_SOURCE_IP);

    final PreAuthTokenSourceTrustAuthenticationProvider underTestWithList = new PreAuthTokenSourceTrustAuthenticationProvider(
            trustedIPAddresses);

    // test, should throw authentication exception
    final Authentication authenticate = underTestWithList.authenticate(token);
    try {
        assertThat(authenticate.isAuthenticated()).isTrue();
        fail("as source is not trusted.");
    } catch (final InsufficientAuthenticationException e) {

    }
}
PieAccessDecisionManager.java 文件源码 项目:pie 阅读 23 收藏 0 点赞 0 评论 0
@Override
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes)
        throws AccessDeniedException, InsufficientAuthenticationException {

    if (!(object instanceof MethodInvocation)) {
        throw new IllegalStateException("Only operates on methods.");
    }
    MethodInvocation methodInvocation = (MethodInvocation)object;

    Role role = null;
    if (authentication != null && authentication.getAuthorities().size() > 0) {
        role = Role.valueOf(authentication.getAuthorities().iterator().next().getAuthority());
    }
    if (role == null) {
        throw new AccessDeniedException("Secured method must have an authenticated role.");
    }

    if (!policyEnforcer.getPolicy().implies(role, methodInvocation.getThis().getClass(), methodInvocation.getMethod())) {
        policyEnforcer.getPolicy().logViolation(role, methodInvocation.getThis().getClass(), methodInvocation.getMethod());
        if (!policyEnforcer.getPolicyConfig().isReportOnlyMode()) {
            throw new AccessDeniedException("Access Denied");
        }
    }
}
AccessFilterTest.java 文件源码 项目:artifactory 阅读 27 收藏 0 点赞 0 评论 0
public void testAuthenticationChallenge() throws IOException, ServletException {
    ArtifactoryHome.bind(new ArtifactoryHome(new File("./target/test/testAuthenticationChallenge")));
    ArtifactoryHome.get().getArtifactoryProperties().setProperty(
            ConstantValues.locksTimeoutSecs.getPropertyName(), "10");
    ArtifactoryBasicAuthenticationEntryPoint authenticationEntryPoint =
            new ArtifactoryBasicAuthenticationEntryPoint();
    HttpServletRequest request = createMock(HttpServletRequest.class);

    HttpServletResponse response = createMock(HttpServletResponse.class);
    response.addHeader("WWW-Authenticate", "Basic realm=\"Artifactory Realm\"");
    response.setContentType(MediaType.APPLICATION_JSON_VALUE);
    response.setStatus(401);
    PrintWriter printWriter = createMock(PrintWriter.class);
    printWriter.write(anyObject(String.class));
    expect(response.getWriter()).andReturn(printWriter);
    expect(request.getRequestURI()).andReturn("testuri");
    expect(request.getHeader("Request-Agent")).andStubReturn("xx");
    replay(request, response, printWriter);
    authenticationEntryPoint.commence(request, response,
            new InsufficientAuthenticationException("Authentication required"));
    verify(response);
}
MyAccessDecisionManager.java 文件源码 项目:gomall.la 阅读 30 收藏 0 点赞 0 评论 0
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes)
        throws AccessDeniedException, InsufficientAuthenticationException {
    log.debug("decide calling {},{}", object, configAttributes);
    if (configAttributes == null) {
        return;
    }
    System.out.println("decide " + object.toString()); // object is a URL.
    Iterator<ConfigAttribute> ite = configAttributes.iterator();
    while (ite.hasNext()) {
        ConfigAttribute ca = ite.next();
        String needRole = ((SecurityConfig) ca).getAttribute();
        for (GrantedAuthority ga : authentication.getAuthorities()) {
            if (needRole.equals(ga.getAuthority())) { // ga is user's role.
                return;
            }
        }
    }
    throw new AccessDeniedException("no right");
}
KarakuUserService.java 文件源码 项目:karaku 阅读 30 收藏 0 点赞 0 评论 0
/**
 * Localiza al usuario basándose en el nombre del usuario.
 * 
 * @param username
 *            el nombre del usuario que identifica al usuario cuyos datos se
 *            requiere.
 * @return la información del usuario.
 */
@Override
public UserDetails loadUserByUsername(String uid) {

    KarakuUser user = new KarakuUser();
    user.setUserName(uid);
    user.addRoles(loadAuthoritiesByDn(uid));

    String permiso = propertiesUtil.get(BASIC_PERMISSION_KEY,
            BASIC_PERMISSION_KEY_DEFAULT);

    boolean allow = false;
    for (GrantedAuthority o : user.getAuthorities()) {
        if (o.getAuthority().equals(permiso)) {
            allow = true;
        }
    }
    if (!allow) {
        throw new InsufficientAuthenticationException(
                "No posee privilegios para este sistema");
    }
    return user;
}
ResourceAccessDecisionManager.java 文件源码 项目:zxl 阅读 35 收藏 0 点赞 0 评论 0
@Override
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
    if (configAttributes == null) {
        return;
    }
    Iterator<ConfigAttribute> iterator = configAttributes.iterator();
    while (iterator.hasNext()) {
        ConfigAttribute configAttribute = iterator.next();
        String needPermission = configAttribute.getAttribute();
        for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
            if (needPermission.equals(grantedAuthority.getAuthority())) {
                return;
            }
        }
    }
    throw new AccessDeniedException("权限不足!");
}
SecuritySessionResource.java 文件源码 项目:secure-data-service 阅读 29 收藏 0 点赞 0 评论 0
/**
 * Method processing HTTP GET requests to debug resource, producing "application/json" MIME
 * media
 * type.
 *
 * @return SecurityContext that will be send back as a response of type "application/json".
 */
@GET
@Path("debug")
public SecurityContext sessionDebug() {

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();

    if (auth == null) {
        throw new InsufficientAuthenticationException("User must be logged in");
    } else if (auth instanceof OAuth2Authentication) {
        if (((OAuth2Authentication) auth).getUserAuthentication() instanceof AnonymousAuthenticationToken) {
            throw new InsufficientAuthenticationException("User must be logged in");
        }
    } else if (auth instanceof AnonymousAuthenticationToken) {
        throw new InsufficientAuthenticationException("User must be logged in");
    }

    return SecurityContextHolder.getContext();
}
InsufficientAuthenticationHandler.java 文件源码 项目:secure-data-service 阅读 34 收藏 0 点赞 0 评论 0
@Override
public Response toResponse(InsufficientAuthenticationException exception) {
    Status status = Response.Status.UNAUTHORIZED;
    String wwwAuthHeader = this.authUrl;
    URI requestUri = (uriInfo == null) ? null : uriInfo.getRequestUri();

    //If we have an embedded OAuth exception, then put the error information in the www-auth header per oauth spec 
    //http://tools.ietf.org/html/rfc6750 see sec 3
    //Otherwise put the auth url in the header
    if (exception.getCause() != null && exception.getCause() instanceof OAuthAccessException) {
        OAuthAccessException oauthEx = (OAuthAccessException) exception.getCause();
        wwwAuthHeader = "Bearer error=\"" + oauthEx.getType().toString() + "\", error_description=\"" + oauthEx.getMessage() + "\"";
    }

    MediaType errorType = MediaType.APPLICATION_JSON_TYPE;
    if(this.headers.getMediaType() == MediaType.APPLICATION_XML_TYPE) {
        errorType = MediaType.APPLICATION_XML_TYPE;
    }

    auditLogger.audit(securityEventBuilder.createSecurityEvent(getThrowingClassName(exception), requestUri, "Access Denied: "
            + exception.getMessage(), false));

    return Response.status(status).entity(new ErrorResponse(status.getStatusCode(), status.getReasonPhrase(),
            "Access DENIED: " + exception.getMessage())).header(HttpHeaders.WWW_AUTHENTICATE, wwwAuthHeader).type(errorType).build();
}
MMTAccessDecisionManager.java 文件源码 项目:mmt 阅读 25 收藏 0 点赞 0 评论 0
@Override
public void decide(Authentication authentication, Object object,
        Collection<ConfigAttribute> configAttributes)
        throws AccessDeniedException, InsufficientAuthenticationException {
    if (configAttributes == null)
        return;
    // 所请求的资源拥有的权限(一个资源对多个权限)
    Iterator<ConfigAttribute> iterator = configAttributes.iterator();
    while (iterator.hasNext()) {
        ConfigAttribute configAttribute = iterator.next();
        // 访问所请求资源所需要的权限
        String needPermission = configAttribute.getAttribute();
        // 用户所拥有的权限authentication
        for (GrantedAuthority ga : authentication.getAuthorities())
            if (needPermission.equals(ga.getAuthority()))
                return;
    }
    // 没有权限
    throw new AccessDeniedException("拒绝访问。");
}
RegisterController.java 文件源码 项目:users-service 阅读 34 收藏 0 点赞 0 评论 0
@PostMapping("/{userId}/cancel")
ResponseEntity<Void> registerCancel(@PathVariable String userId,
                                    @RequestBody(required = false) VerifyDto verification,
                                    Authentication auth) {

    // If no verification code is specified:
    if (verification == null) {
        if (can(auth, "CANCEL_CREATE_USER")) {
            if (!mongo.remove(
                query(where("id").is(userId)
                    .and("confirmed").is(false)
                ), User.class
            ).isUpdateOfExisting()) {
                throw new UserNotFoundException();
            }
        } else {
            throw new InsufficientAuthenticationException(
                "Either a verification code or the role " +
                "'CANCEL_CREATE_USER' is required for this action."
            );
        }
    } else {
        if (!mongo.remove(
            query(where("id").is(userId)
                .and("userCreationCode").is(verification.getCode())
            ), User.class
        ).isUpdateOfExisting()) {
            throw new InvalidVerificationCodeException();
        }
    }

    // TODO: Send out email to user

    LOGGER.info("User '" + userId + "' cancelled registration.");
    return new ResponseEntity<>(OK);
}
JWTAuthenticationProvider.java 文件源码 项目:airsonic 阅读 34 收藏 0 点赞 0 评论 0
@Override
public Authentication authenticate(Authentication auth) throws AuthenticationException {
    JWTAuthenticationToken authentication = (JWTAuthenticationToken) auth;
    if(authentication.getCredentials() == null || !(authentication.getCredentials() instanceof String)) {
        logger.error("Credentials not present");
        return null;
    }
    String rawToken = (String) auth.getCredentials();
    DecodedJWT token = JWTSecurityService.verify(jwtKey, rawToken);
    Claim path = token.getClaim(JWTSecurityService.CLAIM_PATH);
    authentication.setAuthenticated(true);

    // TODO:AD This is super unfortunate, but not sure there is a better way when using JSP
    if(StringUtils.contains(authentication.getRequestedPath(), "/WEB-INF/jsp/")) {
        logger.warn("BYPASSING AUTH FOR WEB-INF page");
    } else

    if(!roughlyEqual(path.asString(), authentication.getRequestedPath())) {
        throw new InsufficientAuthenticationException("Credentials not valid for path " + authentication
                .getRequestedPath() + ". They are valid for " + path.asString());
    }

    List<GrantedAuthority> authorities = new ArrayList<>();
    authorities.add(new SimpleGrantedAuthority("IS_AUTHENTICATED_FULLY"));
    authorities.add(new SimpleGrantedAuthority("ROLE_TEMP"));
    return new JWTAuthenticationToken(authorities, rawToken, authentication.getRequestedPath());
}


问题


面经


文章

微信
公众号

扫码关注公众号