GVKun编程网logo

Java Future-Spring Authentication在AuditorAware中为空(java auth fail)

5

在本文中,您将会了解到关于JavaFuture-SpringAuthentication在AuditorAware中为空的新资讯,同时我们还将为您解释javaauthfail的相关在本文中,我们将带你

在本文中,您将会了解到关于Java Future-Spring Authentication在AuditorAware中为空的新资讯,同时我们还将为您解释java auth fail的相关在本文中,我们将带你探索Java Future-Spring Authentication在AuditorAware中为空的奥秘,分析java auth fail的特点,并给出一些关于asp.net-core – options的用途.AutomaticAuthenticate with UseJwtBearerAuthentication、org.springframework.security.authentication.AbstractAuthenticationToken的实例源码、org.springframework.security.authentication.AnonymousAuthenticationToken的实例源码、org.springframework.security.authentication.AuthenticationCredentialsNotFoundException的实例源码的实用技巧。

本文目录一览:

Java Future-Spring Authentication在AuditorAware中为空(java auth fail)

Java Future-Spring Authentication在AuditorAware中为空(java auth fail)

这是我的情况:

我的应用程序启用了Mongo
Auditing,并使用了自定义的AuditorAware,可从中获取当前用户SecurityContext。这在同步方法中效果很好,并且当前的审计程序已成功保存,但是我无法使其在@Async方法中正常工作。

我有一个异步方法(CompletableFuture),可对Mongo数据库进行一些更新。当AuditorAware.getCurrentAuditor()被调用时,没有任何身份验证信息存在,我不能让现任核数师(SecurityContextHolder.getContext().getAuthentication()回报null)。

@Overridepublic User getCurrentAuditor() {   Authentication authentication = SecurityContextHolder.getContext().getAuthentication();   if (authentication == null || !authentication.isAuthenticated()                || authentication instanceof AnonymousAuthenticationToken) {            log.error("Not authenticated");            return null;    }    [...]}

我正在使用DelegatingSecurityContextAsyncTaskExecutor

@Configuration@EnableAsyncpublic class AsyncConfig implements AsyncConfigurer {    @Override    public Executor getAsyncExecutor() {        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();        executor.setCorePoolSize(20);        executor.setMaxPoolSize(100);        executor.setQueueCapacity(200);        executor.initialize();        return new DelegatingSecurityContextAsyncTaskExecutor(executor);    }    @Override    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {        return new ItacaExceptionHandler();    }}

如何使它正常工作?

答案1

小编典典

Spring安全上下文始终绑定到Threadlocal。

可能您可能还需要为安全上下文设置MODE_INHERITABLETHREADLOCAL。

@Beanpublic MethodInvokingFactoryBean methodInvokingFactoryBean() {    MethodInvokingFactoryBean methodInvokingFactoryBean = new MethodInvokingFactoryBean();    methodInvokingFactoryBean.setTargetClass(SecurityContextHolder.class);    methodInvokingFactoryBean.setTargetMethod("setStrategyName");    methodInvokingFactoryBean.setArguments(new String[]{SecurityContextHolder.MODE_INHERITABLETHREADLOCAL});    return methodInvokingFactoryBean;}

http://www.ogrigas.eu/spring/2010/04/inherit-spring-security-context-in-
child-threads

asp.net-core – options的用途.AutomaticAuthenticate with UseJwtBearerAuthentication

asp.net-core – options的用途.AutomaticAuthenticate with UseJwtBearerAuthentication

在将代码库从ASP 5 beta 7更新到RC1-final之后,我开始从JwtBearer中间件接收此异常

Unable to cast object of type 'Newtonsoft.Json.Linq.JArray' to type 'System.IConvertible'.

到目前为止我可以看到的决定因素似乎是选项的设置.AutomaticAuthenticate.如果这是真的,那么我得到例外,否则,我没有.

什么是AutomaticAuthenticate,为什么我需要启用它?

app.UseJwtBearerAuthentication(options =>
    {
        options.AutomaticAuthenticate = true; 
    }

这是完整的堆栈跟踪:

at System.Convert.ToInt32(Object value,IFormatProvider provider)
   at System.IdentityModel.Tokens.Jwt.JwtPayload.GetIntClaim(String claimType)
   at System.IdentityModel.Tokens.Jwt.JwtPayload.get_Nbf()
   at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.Validatetoken(String token,TokenValidationParameters validationParameters,SecurityToken& validatedToken)
   at Microsoft.AspNet.Authentication.JwtBearer.JwtBearerHandler.<HandleAuthenticateAsync>d__1.MoveNext()
--- End of stack trace from prevIoUs location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptiondispatchInfo.Throw()
   at Microsoft.AspNet.Authentication.JwtBearer.JwtBearerHandler.<HandleAuthenticateAsync>d__1.MoveNext()
--- End of stack trace from prevIoUs location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.AspNet.Authentication.AuthenticationHandler`1.<InitializeAsync>d__48.MoveNext()
--- End of stack trace from prevIoUs location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at Microsoft.AspNet.Authentication.AuthenticationMiddleware`1.<Invoke>d__18.MoveNext()
--- End of stack trace from prevIoUs location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at Api.Startup.<<Configure>b__9_0>d.MoveNext() in ...\Startup.cs:line 156

更新根本原因

我们的代码库正在为nbf,exp和iat创建重复声明.这就解释了为什么get_Nbf在堆栈跟踪中以及关于“JArray”的抱怨,因为每个值都是数组而不是值.

解决方法

如果设置为true,则中间件将在每个入站请求上运行,查找JWT令牌,如果存在,则将验证它,如果有效则从中创建标识并将其添加到当前用户.

如果它没有发生,那么您需要通过在authorize属性中指定承载的方案来请求中间件设置标识.

[Authorize(AuthenticationSchemes = "YourBearerSchemeName")]

或者你在政策中设置这个;

options.AddPolicy("RequireBearer",policy =>
{
    policy.AuthenticationSchemes.Add("YourBearerSchemeName");
    policy.RequireAuthenticatedUser();

});

因此,通过将其设置为false,您实际上并没有运行持有者的东西,直到您要求它为止,您只是将异常关闭直到稍后.

org.springframework.security.authentication.AbstractAuthenticationToken的实例源码

org.springframework.security.authentication.AbstractAuthenticationToken的实例源码

项目:graviteeio-access-management    文件:CustomTokenGranter.java   
@Override
protected OAuth2Authentication getoAuth2Authentication(ClientDetails client,TokenRequest tokenRequest) {
    try {
        Authentication userAuth = null;
        User user = extensionGrantProvider.grant(convert(tokenRequest));
        if (user != null) {
            userAuth = new UsernamePasswordAuthenticationToken(user,"",AuthorityUtils.NO_AUTHORITIES);
            if (extensionGrant.iscreateuser()) {
                Map<String,String> parameters = new LinkedHashMap<String,String>(tokenRequest.getRequestParameters());
                parameters.put(RepositoryProviderUtils.soURCE,extensionGrant.getIdentityProvider());
                ((AbstractAuthenticationToken) userAuth).setDetails(parameters);
                eventPublisher.publishAuthenticationSuccess(userAuth);
            }
        }

        OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client,tokenRequest);
        return new OAuth2Authentication(storedOAuth2Request,userAuth);
    } catch (InvalidGrantException e) {
        throw new org.springframework.security.oauth2.common.exceptions.InvalidGrantException(e.getMessage(),e);
    }
}
项目:communote-server    文件:ConfluenceAuthenticationProvider.java   
/**
 * {@inheritDoc}
 */
@Override
protected Authentication createSuccessAuthentication(UserDetails details,Authentication authentication) {
    if (details == null || authentication == null) {
        return null;
    }
    AbstractAuthenticationToken auth = null;
    if (authentication instanceof UsernamePasswordAuthenticationToken) {
        auth = new UsernamePasswordAuthenticationToken(details,authentication.getCredentials(),details.getAuthorities());
    } else if (authentication instanceof ConfluenceAuthenticationToken) {
        auth = new ConfluenceAuthenticationToken(details,(String) authentication.getCredentials(),details.getAuthorities());
    }
    if (auth != null) {
        auth.setDetails(authentication.getDetails());
    }
    return auth;
}
项目:opencucina    文件:CurrentUserChannelInterceptorTest.java   
/**
 * JAVADOC Method Level Comments
 *
 * @throws Exception JAVADOC.
 */
@Before
public void setUp()
    throws Exception {
    MockitoAnnotations.initMocks(this);
    interceptor = new CurrentUserChannelInterceptor(systemUserService,userAccessor);

    if (null == SecurityContextHolder.getContext()) {
        SecurityContextHolder.setContext(new SecurityContextImpl());
    }

    SecurityContext context = SecurityContextHolder.getContext();

    user = new User();
    user.setName("user");

    AbstractAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(user,null);

    authToken.setDetails("pipipi");
    context.setAuthentication(authToken);
}
项目:springboot-jersey-example    文件:CustomAuthenticationProvider.java   
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    // get username and password
    String username = (authentication.getPrincipal() == null) ? "" : authentication.getName();
    String password = (authentication.getCredentials() == null) ? "" : authentication.getCredentials().toString();

    // check credentials
    if (userService.checkCredentials(username,password)) {
        // init return value
        AbstractAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username,null,new ArrayList<>());

        // set user object
        authenticationToken.setDetails(userService.getUserByUsername(username));

        // return user details
        return authenticationToken;
    }

    // indicate invalid credentials
    throw new InternalAuthenticationServiceException("Unable to authenticate");
}
项目:eMonocot    文件:RestAPIKeyAuthenticationFilter.java   
@Override
public Authentication attemptAuthentication(HttpServletRequest request,HttpServletResponse response) throws AuthenticationException,IOException,servletexception {

    String apikeyvalue = decodeParameterValue(request,API_KEY_ParaMETER_NAME);
    logger.debug("attemptAuthentication " + apikeyvalue);

    AbstractAuthenticationToken authRequest = createAuthenticationToken(
            apikeyvalue,new RestCredentials());

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

    return this.getAuthenticationManager().authenticate(authRequest);
}
项目:motech    文件:UserContextServiceImpl.java   
@Override
@Transactional
public void refreshUserContextIfActive(String userName) {
    LOGGER.info("Refreshing context for user: {}",userName);

    MotechUser user = motechUsersDao.findByUserName(userName);
    Collection<HttpSession> sessions = sessionHandler.getAllSessions();

    for (HttpSession session : sessions) {
        SecurityContext context = (SecurityContext) session.getAttribute("SPRING_Security_CONTEXT");

        if (context != null) {
            Authentication authentication = context.getAuthentication();
            AbstractAuthenticationToken token;
            User userInSession = (User) authentication.getPrincipal();
            if (userInSession.getUsername().equals(userName)) {
                token = getToken(authentication,user);
                context.setAuthentication(token);
            }
        }
    }
    LOGGER.info("Refreshed context for user: {}",userName);

}
项目:swagger-cxf-rest-skeleton    文件:TokenAuthenticationFilter.java   
/**
 * Attempt to authenticate request - basically just pass over to another method to authenticate request headers
 */
@Override
public Authentication attemptAuthentication(final HttpServletRequest request,final HttpServletResponse response) throws AuthenticationException,servletexception {
    String token = null;
    if (null != request.getCookies()) {
        for (final Cookie cookie : request.getCookies()) {
            if (COOKIE_Security_TOKEN.equals(cookie.getName())) {
                token = cookie.getValue();
            }
        }
    }

    if (token == null) {
        logger.info("No token found request:" + request.getRequestURI());
        throw new AuthenticationServiceException(messageformat.format("Error | {0}","No Token"));
    }

    logger.info("token found:" + token + " request:" + request.getRequestURI());
    final AbstractAuthenticationToken userAuthenticationToken = authUserByToken(token);
    if (userAuthenticationToken == null) {
        throw new AuthenticationServiceException(messageformat.format("Error | {0}","Bad Token"));
    }
    return userAuthenticationToken;
}
项目:rave    文件:DefaultUserService.java   
private SecurityContext createContext(final User user) {
    SecurityContext securityContext = new SecurityContextImpl();
    securityContext.setAuthentication(new AbstractAuthenticationToken(user.getAuthorities()) {
        private static final long serialVersionUID = 1L;

        @Override
        public Object getCredentials() {
            return "N/A";
        }

        @Override
        public Object getPrincipal() {
            return user;
        }

        @Override
        public boolean isAuthenticated() {
            return true;
        }
    });
    return securityContext;
}
项目:rave    文件:DefaultUserServiceTest.java   
@Test
public void getAuthenticatedUser_validUser() {
    final User authUser = new UserImpl(USER_ID);
    AbstractAuthenticationToken auth = createNiceMock(AbstractAuthenticationToken.class);
    expect(auth.getPrincipal()).andReturn(authUser).anyTimes();
    replay(auth);

    SecurityContext context = new SecurityContextImpl();
    context.setAuthentication(auth);
    SecurityContextHolder.setContext(context);

    User result = service.getAuthenticatedUser();

    assertthat(result,is(sameInstance(authUser)));
    verify(auth);
}
项目:rave    文件:RenderServiceIntegrationTest.java   
@SuppressWarnings("unchecked")
@Before
public void setup() throws sqlException {
    restOperations = EasyMock.createNiceMock(RestOperations.class);
    EasyMock.expect(restOperations.postForObject(EasyMock.anyObject(String.class),EasyMock.anyObject(String.class),EasyMock.anyObject(Class.class)))
            .andReturn(VALID_MetaDATA);
    EasyMock.replay(restOperations);

    //Replace the real restOperations instance with a mock -- otherwise the call for gadget Metadata would fail since
    //we don't have a shindig server available to hit.
    ReflectionTestUtils.setField(MetadataRepository,"restOperations",restOperations);

    //Setup a mock authenticated user
    final User authUser = new UserImpl(VALID_USER_ID,VALID_USER_NAME);
    AbstractAuthenticationToken auth = EasyMock.createNiceMock(AbstractAuthenticationToken.class);
    EasyMock.expect(auth.getPrincipal()).andReturn(authUser).anyTimes();
    EasyMock.replay(auth);

    SecurityContext context = new SecurityContextImpl();
    context.setAuthentication(auth);
    SecurityContextHolder.setContext(context);
}
项目:springchat    文件:AuthenticationRest.java   
@RequestMapping(value = "/rest/auth",method = RequestMethod.POST,produces = {"application/json"})
@ResponseBody
public AuthenticationResultDto postUser(@RequestParam("user") String user,HttpServletRequest request) {
    AuthenticationResultDto dto = new AuthenticationResultDto();
    dto.setSessionId(request.getSession().getId());
    try {
        // Must be called from request filtered by Spring Security,otherwise SecurityContextHolder is not updated
        AbstractAuthenticationToken token = new UsernamePasswordAuthenticationToken(user,"");
        token.setDetails(new WebAuthenticationDetails(request));
        Authentication authentication = authenticationManager.authenticate(token);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        dto.setSuccess(Boolean.TRUE);
        request.getSession().setAttribute("authenticated",Boolean.TRUE);
    } catch (Exception e) {
        SecurityContextHolder.getContext().setAuthentication(null);
        dto.setSuccess(Boolean.FALSE);
        request.getSession().setAttribute("authenticated",Boolean.FALSE);
    }
    return dto;
}
项目:wildfly-camel    文件:UsernamePasswordAuthenticationAdapter.java   
protected Authentication convertToAuthentication(Subject subject) {
    AbstractAuthenticationToken authToken = null;
    Set<UsernamePasswordPrincipal> principalSet  = subject.getPrincipals(UsernamePasswordPrincipal.class);
    if (principalSet.size() > 0) {
        UsernamePasswordPrincipal upp = principalSet.iterator().next();
        authToken = new UsernamePasswordAuthenticationToken(upp.getName(),upp.getpassword());
    }
    if (authToken != null) {
        Set<DomainPrincipal> auxset = subject.getPrincipals(DomainPrincipal.class);
        if (auxset.size() > 0) {
            String domain = auxset.iterator().next().getName();
            authToken.setDetails(domain);
        }
    }
    return authToken;
}
项目:airsonic    文件:LoginFailureListener.java   
@Override
public void onApplicationEvent(ApplicationEvent event) {
    if (event instanceof AbstractAuthenticationFailureEvent) {
        if (event.getSource() instanceof AbstractAuthenticationToken) {
            AbstractAuthenticationToken token = (AbstractAuthenticationToken) event.getSource();
            Object details = token.getDetails();
            if (details instanceof WebAuthenticationDetails) {
                LOG.info("Login Failed from [" + ((WebAuthenticationDetails) details).getRemoteAddress() + "]");
            }
        }
    }

}
项目:haven-platform    文件:SecurityUtils.java   
/**
 * Set auth details if it possible
 * @param authentication
 * @param details
 * @return  true if update details is success
 */
public static boolean setDetailsIfPossible(Authentication authentication,Object details) {
    if(authentication instanceof AbstractAuthenticationToken) {
        ((AbstractAuthenticationToken)authentication).setDetails(details);
        return true;
    }
    return false;
}
项目:opencucina    文件:SystemUserMethodInterceptorTest.java   
/**
 * JAVADOC Method Level Comments
 *
 * @throws Throwable JAVADOC.
 */
@Test
public void test()
    throws Throwable {
    //create authentication
    User user = new User();

    user.setUsername("loggedin");

    //set security
    AbstractAuthenticationToken authToken = setSecurity(user,true);

    //mock systemUserService returns username
    String systemUsername = "ADMIN";

    when(systemUserService.getUsername()).thenReturn(systemUsername);

    SystemUserMethodInterceptor interceptor = new SystemUserMethodInterceptor(userAccessor,systemUserService);

    interceptor.invoke(methodInvocation);
    //mock authenticatioNService call
    verify(userAccessor).forceUserToContext(systemUsername);
    verify(methodInvocation).proceed();

    //test it switches back
    assertEquals(CurrentUserAccessor.currentAuthentication(),authToken);
}
项目:motech    文件:UserContextServiceImpl.java   
@Override
@Transactional
public void refreshAllUsersContextIfActive() {
    Collection<HttpSession> sessions = sessionHandler.getAllSessions();
    MotechUser user;

    LOGGER.info("Refreshing context for all active users,number of sessions: {}",sessions.size());

    for (HttpSession session : sessions) {
        SecurityContext context = (SecurityContext) session.getAttribute("SPRING_Security_CONTEXT");

        if (context != null) {
            Authentication authentication = context.getAuthentication();
            AbstractAuthenticationToken token;

            User userInSession = (User) authentication.getPrincipal();
            user = motechUsersDao.findByUserName(userInSession.getUsername());

            if (user == null) {
                LOGGER.warn("User {} has a session,but does not exist",userInSession.getUsername());
            } else {
                LOGGER.debug("Refreshing context for user {}",user.getUserName());
                token = getToken(authentication,user);
                context.setAuthentication(token);
            }
        }
    }

    LOGGER.info("Refreshed context for all active users");
}
项目:swagger-cxf-rest-skeleton    文件:TokenAuthenticationFilter.java   
/**
 * authenticate the user based on token
 *
 * @return
 */
private AbstractAuthenticationToken authUserByToken(final String token) {

    final UserToken userToken = userTokenDao.findByAuthenticationToken(token);
    if (null == userToken) {
        return null;
    }

    final AbstractAuthenticationToken authToken = new AuthenticationToken(userToken);
    return authToken;
}
项目:rest-retro-sample    文件:OAuthPostAuthListener.java   
@Override
public void onApplicationEvent(AbstractAuthenticationEvent event) {
    Authentication authentication = event.getAuthentication();

    if (event instanceof AuthenticationSuccessEvent) {
      ResourceOwnerPasswordResourceDetails resource = getResourceOwnerPasswordResourceDetails();
      resource.setScope(Arrays.asList("words"));
      resource.setUsername(authentication.getName());
      resource.setPassword(authentication.getCredentials().toString());

      try {
          OAuth2Accesstoken accesstoken = accesstokenProvider.obtainAccesstoken(resource,new DefaultAccesstokenRequest());
          log.debug("Access token request succeeded for user: '{}',new token is '{}'",resource.getUsername(),accesstoken.getValue());
          if (authentication instanceof AbstractAuthenticationToken && authentication.getDetails() instanceof CustomAuthenticationDetails) {
              ((CustomAuthenticationDetails) ((AbstractAuthenticationToken) authentication).getDetails())
                .setBearer(accesstoken.getValue());
              log.debug("Access token was added to authentication as details");
          } else if (log.isDebugEnabled()) {
              log.debug("Access token Could not be added to authentication as details");
          }
      } catch (Exception e) {
          log.error("Access token request Failed for user: '" + resource.getUsername() + "'",e);
      }
    }
    if (authentication instanceof CredentialsContainer) {
           // Authentication is complete. Remove credentials and other secret data from authentication
           ((CredentialsContainer)authentication).eraseCredentials();
       }

}
项目:rest-retro-sample    文件:OAuthPostAuthListener.java   
@Override
public void onApplicationEvent(AbstractAuthenticationEvent event) {
    Authentication authentication = event.getAuthentication();
    if (event instanceof AuthenticationSuccessEvent) {

      ResourceOwnerPasswordResourceDetails resource = getResourceOwnerPasswordResourceDetails();
      resource.setScope(Arrays.asList("words"));
      resource.setUsername(authentication.getName());
      resource.setPassword(authentication.getCredentials().toString());

      try {
          OAuth2Accesstoken accesstoken = accesstokenProvider.obtainAccesstoken(resource,e);
      }
    }
    if (authentication instanceof CredentialsContainer) {
           // Authentication is complete. Remove credentials and other secret data from authentication
           ((CredentialsContainer)authentication).eraseCredentials();
       }

}
项目:rave    文件:DefaultUserServiceTest.java   
@Test(expected = SecurityException.class)
public void getAuthenticatedUser_wrongPrincipalType() {
    AbstractAuthenticationToken auth = createNiceMock(AbstractAuthenticationToken.class);
    expect(auth.getPrincipal()).andReturn(USER_ID).anyTimes();
    replay(auth);

    SecurityContext context = new SecurityContextImpl();
    SecurityContextHolder.setContext(context);

    service.getAuthenticatedUser();
    verify(auth);
}
项目:adjule    文件:UserAuthEndpoint.java   
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/logged",method = RequestMethod.GET)
public UserAuthView isLogged(Principal principal) {
    UserAuthView userAuthView = new UserAuthView();
    if (principal instanceof AbstractAuthenticationToken) {
        userAuthView = (UserAuthView) ((AbstractAuthenticationToken) principal).getPrincipal();
    }
    if (SecurityUtils.isSwitchedUser()) {
        userAuthView.setSwitchedUser(true);
    }
    return userAuthView;
}
项目:oauth-client-master    文件:DefaultAuthenticationHandler.java   
/**
 * Default implementation returns the user authentication associated with the auth token,if the token is provided. Otherwise,the consumer authentication
 * is returned.
 *
 * @param request The request that was successfully authenticated.
 * @param authentication The consumer authentication (details about how the request was authenticated).
 * @param authToken The OAuth token associated with the authentication. This token MAY be null if no authenticated token was needed to successfully
 * authenticate the request (for example,in the case of 2-legged OAuth).
 * @return The authentication.
 */
public Authentication createAuthentication(HttpServletRequest request,ConsumerAuthentication authentication,OAuthAccessproviderToken authToken) {
  if (authToken != null) {
    Authentication userAuthentication = authToken.getUserAuthentication();
    if (userAuthentication instanceof AbstractAuthenticationToken) {
      //initialize the details with the consumer that is actually making the request on behalf of the user.
      ((AbstractAuthenticationToken) userAuthentication).setDetails(new OAuthAuthenticationDetails(request,authentication.getConsumerDetails()));
    }
    return userAuthentication;
  }

  return authentication;
}
项目:game-on    文件:DummyUserDetailsService.java   
@Override
    public UserDetails loadUserDetails(AbstractAuthenticationToken token)
            throws UsernameNotFoundException {

        GameonUser user =  new GameonUser(token.getName(),token.getAuthorities() );

//      OpenIDAuthenticationToken   
        if(token instanceof OpenIDAuthenticationToken){         
            List<OpenIDAttribute> attributes = ((OpenIDAuthenticationToken)token).getAttributes();
            user.setopenIDAttributes(attributes);
        }

        return user;
    }
项目:spring-auth-example    文件:CustomresourceOwnerPasswordTokenGranter.java   
@Override
protected OAuth2Authentication getoAuth2Authentication(ClientDetails client,TokenRequest tokenRequest) {

  Map<String,String>(
      tokenRequest.getRequestParameters());
  String username = parameters.get("username");
  String password = parameters.get("password");
  String clientId = client.getClientId();
  // Protect from downstream leaks of password
  parameters.remove("password");

  Authentication userAuth;
  if ("foo_app".equalsIgnoreCase(clientId)) {
    userAuth = new FooUsernamePasswordAuthenticationToken(username,password);
  } else if ("bar_app".equalsIgnoreCase(clientId)) {
    userAuth = new BarUsernamePasswordAuthenticationToken(username,password);
  } else {
    throw new InvalidGrantException("UnkNown client: " + clientId);
  }

  ((AbstractAuthenticationToken) userAuth).setDetails(parameters);
  try {
    userAuth = authenticationManager.authenticate(userAuth);
  } catch (AccountStatusException ase) {
    //covers expired,locked,disabled cases (mentioned in section 5.2,draft 31)
    throw new InvalidGrantException(ase.getMessage());
  } catch (BadCredentialsException e) {
    // If the username/password are wrong the spec says we should send 400/invalid grant
    throw new InvalidGrantException(e.getMessage());
  }
  if (userAuth == null || !userAuth.isAuthenticated()) {
    throw new InvalidGrantException(
        "Could not authenticate user: " + username);
  }

  OAuth2Request storedOAuth2Request = getRequestFactory()
      .createOAuth2Request(client,tokenRequest);
  return new OAuth2Authentication(storedOAuth2Request,userAuth);
}
项目:eMonocot    文件:RestAPIKeyAuthenticationFilter.java   
private AbstractAuthenticationToken createAuthenticationToken(
        String apikeyvalue,RestCredentials restCredentials) {
    return new RestAuthenticationToken(apikeyvalue,restCredentials);
}
项目:incubator-atlas    文件:AtlasKnoxSSOAuthenticationFilter.java   
@Override
public void doFilter(ServletRequest servletRequest,ServletResponse servletResponse,FilterChain filterChain) throws IOException,servletexception {

    HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;

    AtlasResponseRequestWrapper responseWrapper = new AtlasResponseRequestWrapper(httpResponse);
    responseWrapper.setHeader("x-frame-options","DENY");

    if (!ssoEnabled) {
        filterChain.doFilter(servletRequest,servletResponse);
        return;
    }

    HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
    if (LOG.isDebugEnabled()) {
        LOG.debug("Knox doFilter {}",httpRequest.getRequestURI());
    }

    if (httpRequest.getSession() != null && httpRequest.getSession().getAttribute("locallogin") != null) {
        servletRequest.setAttribute("ssoEnabled",false);
        filterChain.doFilter(servletRequest,servletResponse);
        return;
    }

    if (jwtProperties == null || isAuthenticated()) {
        filterChain.doFilter(servletRequest,servletResponse);
        return;
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Knox ssoEnabled  {} {}",ssoEnabled,httpRequest.getRequestURI());
    }
    //if jwt properties are loaded and is current not authenticated then it will go for sso authentication
    //Note : Need to remove !isAuthenticated() after knoxsso solve the bug from cross-origin script
    HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
    String serializedJWT = getJWTFromCookie(httpRequest);
    // if we get the hadoop-jwt token from the cookies then will process it further
    if (serializedJWT != null) {
        SignedJWT jwtToken = null;
        try {
            jwtToken = SignedJWT.parse(serializedJWT);
            boolean valid = validatetoken(jwtToken);
            //if the public key provide is correct and also token is not expired the process token
            if (valid) {
                String userName = jwtToken.getJWTClaimsSet().getSubject();
                LOG.info("SSO login user : {} ",userName);
                //if we get the userName from the token then log into atlas using the same user
                if (userName != null && !userName.trim().isEmpty()) {
                    List<GrantedAuthority> grantedAuths = AtlasAuthenticationProvider.getAuthoritiesFromUGI(userName);
                    final UserDetails principal = new User(userName,grantedAuths);
                    final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal,grantedAuths);
                    WebAuthenticationDetails webDetails = new WebAuthenticationDetails(httpRequest);
                    ((AbstractAuthenticationToken) finalAuthentication).setDetails(webDetails);
                    authenticationProvider.setSsoEnabled(ssoEnabled);
                    Authentication authentication = authenticationProvider.authenticate(finalAuthentication);
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }

                filterChain.doFilter(servletRequest,httpServletResponse);
            } else {  // if the token is not valid then redirect to knox sso
                redirectToKnox(httpRequest,httpServletResponse,filterChain);
            }
        } catch (ParseException e) {
            LOG.warn("Unable to parse the JWT token",e);
            redirectToKnox(httpRequest,filterChain);
        }
    } else {
        redirectToKnox(httpRequest,filterChain);
    }

}
项目:modinvreg    文件:BaseSpringContextTest.java   
/**
 * @param token
 */
private static void putTokenInContext( AbstractAuthenticationToken token ) {
    SecurityContextHolder.getContext().setAuthentication( token );
}
项目:oauth-client-master    文件:OAuth2AuthenticationProcessingFilter.java   
public void doFilter(ServletRequest req,ServletResponse res,FilterChain chain) throws IOException,servletexception {

    final boolean debug = logger.isDebugEnabled();
    final HttpServletRequest request = (HttpServletRequest) req;
    final HttpServletResponse response = (HttpServletResponse) res;

    try {

        Authentication authentication = tokenExtractor.extract(request);

        if (authentication == null) {
            if (debug) {
                logger.debug("No token in request,will continue chain.");
            }
        }
        else {
            request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_VALUE,authentication.getPrincipal());
            if (authentication instanceof AbstractAuthenticationToken) {
                AbstractAuthenticationToken needsDetails = (AbstractAuthenticationToken) authentication;
                needsDetails.setDetails(authenticationDetailsSource.buildDetails(request));                 
            }
            Authentication authResult = authenticationManager.authenticate(authentication);

            if (debug) {
                logger.debug("Authentication success: " + authResult);
            }

            SecurityContextHolder.getContext().setAuthentication(authResult);

        }
    }
    catch (OAuth2Exception Failed) {
        SecurityContextHolder.clearContext();

        if (debug) {
            logger.debug("Authentication request Failed: " + Failed);
        }

        authenticationEntryPoint.commence(request,response,new InsufficientAuthenticationException(Failed.getMessage(),Failed));

        return;
    }

    chain.doFilter(request,response);
}
项目:eMonocot    文件:RestAPIKeyAuthenticationFilter.java   
/**
 * Provided so that subclasses may configure what is put into the
 * authentication request's details property.
 *
 * @param request
 *            that an authentication request is being created for
 * @param authRequest
 *            the authentication request object that should have its details
 *            set
 */
protected void setDetails(HttpServletRequest request,AbstractAuthenticationToken authRequest) {
    authRequest.setDetails(authenticationDetailsSource
            .buildDetails(request));
}
项目:irplus    文件:UrAuthenticationProcessingFilter.java   
/**
 * Provided so that subclasses may configure what is put into the authentication request's details
 * property.
 *
 * @param request that an authentication request is being created for
 * @param authRequest the authentication request object that should have its details set
 */
protected void setDetails(HttpServletRequest request,AbstractAuthenticationToken authRequest) {
    authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
}

org.springframework.security.authentication.AnonymousAuthenticationToken的实例源码

org.springframework.security.authentication.AnonymousAuthenticationToken的实例源码

项目:KPBlog    文件:ArticleController.java   
@GetMapping("/article/{id}")
public String details(Model model,@PathVariable Integer id) {
    if (!this.articleRepository.exists(id)) {
        return "redirect:/";
    }

    if (!(SecurityContextHolder.getContext().getAuthentication()
        instanceof AnonymousAuthenticationToken)) {
        UserDetails user = (UserDetails) SecurityContextHolder
                .getContext()
                .getAuthentication()
                .getPrincipal();

        User userEntity = this.userRepository.findByEmail(user.getUsername());
        model.addAttribute("user",userEntity);
    }
    Article article = this.articleRepository.findOne(id);

    model.addAttribute("article",article);
    model.addAttribute("view","article/details");
    return "base-layout";
}
项目:Smart-Shopping    文件:RedirectWhenAuthenticatedInterceptor.java   
@Override
public boolean preHandle(HttpServletRequest request,HttpServletResponse response,Object handler)
        throws Exception {

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    boolean isAuthenticated;
    if (authentication != null) {
        isAuthenticated = authentication instanceof AnonymousAuthenticationToken ? false
                : authentication.isAuthenticated();
        if (isAuthenticated) {
            response.setContentType("text/plain");
            sendRedirect(request,response);
            return false; // no need to proceed with the chain as we already dealt with the response
        }
    }
    return true;
}
项目:sns-todo    文件:SecurityUtil.java   
public static String getUserName() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication instanceof UsernamePasswordAuthenticationToken) {
        return authentication.getName();
    }

    if (authentication instanceof OAuth2Authentication) {
        log.info("third part login.authentication:{},user {},from {}",authentication,authentication.getName(),NetworkUtil.getRemoteIp());
        return authentication.getName();
    }

    if (authentication instanceof AnonymousAuthenticationToken) {
        log.warn(" user {} not login,NetworkUtil.getRemoteIp());
        return authentication.getName();
    }

    log.warn("{} isAuthenticated():{},name:{},details:{}",Flag.BizLogFlag.WARN_CHECK,authentication.isAuthenticated(),authentication.getDetails());
    throw new ApiBizException(GlobalCode.UNKNowN);
}
项目:nixmash-blog    文件:PostServiceImpl.java   
@Override
public boolean canUpdatePost(Authentication authentication,Long postId) {

    if (authentication instanceof AnonymousAuthenticationToken)
        return false;

    CurrentUser currentUser = (CurrentUser) authentication.getPrincipal();

    Post post = null;
    try {
        post = getPostById(postId);
    } catch (PostNotFoundException e) {
        logger.error("Post not found for PostId {} ",postId);
        return false;
    }

    Long postUserId = post.getUserId();
    return currentUser.getId().equals(postUserId);
}
项目:grpc-spring-security-demo    文件:BasicAuthenticationInterceptor.java   
private boolean authenticationIsrequired(String username) {
    Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();
    if (Objects.isNull(existingAuth) || !existingAuth.isAuthenticated()) {
        return true;
    }

    if (existingAuth instanceof UsernamePasswordAuthenticationToken
            && !existingAuth.getName().equals(username)) {
        return true;
    }

    if (existingAuth instanceof AnonymousAuthenticationToken) {
        return true;
    }

    return false;
}
项目:grpc-spring-security-demo    文件:AnonymousAuthenticationInterceptor.java   
@Override
public <ReqT,RespT> ServerCall.Listener<ReqT> interceptCall(
        ServerCall<ReqT,RespT> call,Metadata headers,ServerCallHandler<ReqT,RespT> next) {
    if (Objects.isNull(SecurityContextHolder.getContext().getAuthentication())) {
        SecurityContextHolder.getContext().setAuthentication(new AnonymousAuthenticationToken(key,"anonymousUser",Collections.singletonList(new SimpleGrantedAuthority("ROLE_ANONYMOUS"))));

        log.debug("Populated SecurityContextHolder with anonymous token: {}",SecurityContextHolder.getContext().getAuthentication());
    } else {
        log.debug("SecurityContextHolder not populated with anonymous token,as it already contained: {}",SecurityContextHolder.getContext().getAuthentication());
    }

    return next.startCall(call,headers);
}
项目:spring-cloud-dashboard    文件:SecurityController.java   
/**
 * Return security information. E.g. is security enabled? Which user do you represent?
 */
@ResponseBody
@RequestMapping(method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public SecurityInfoResource getSecurityInfo() {

    final boolean authenticationEnabled = securityProperties.getBasic().isEnabled();

    final SecurityInfoResource securityInfo = new SecurityInfoResource();
    securityInfo.setAuthenticationEnabled(authenticationEnabled);
    securityInfo.add(ControllerLinkBuilder.linkTo(SecurityController.class).withSelfRel());

    if (authenticationEnabled && SecurityContextHolder.getContext() != null) {
        final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (!(authentication instanceof AnonymousAuthenticationToken)) {
            securityInfo.setAuthenticated(authentication.isAuthenticated());
            securityInfo.setUsername(authentication.getName());
        }
    }

    return securityInfo;
}
项目:dawn-marketplace-server    文件:MarketplaceDAO.java   
/**
 * Tests whether or not the current user have access to edit the solution
 * with the given identifier. The user must be an administrator or own the
 * solution.
 *
 * @param identifier
 *            the identifier of the solution
 * @return <code>true</code> if editable
 */
public boolean canEdit(Long identifier) {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication == null || authentication instanceof AnonymousAuthenticationToken) {
        return false;
    }
    Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
    for (GrantedAuthority grantedAuthority : authorities) {
        if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) {
            return true;
        }
    }
    // new solution
    if (identifier == null) {
        return true;
    }
    Account account = accountRepository.findOne(authentication.getName());
    Account a = accountRepository.findAccountBySolutionId(identifier);
    if (account.getUsername().equals(a.getUsername())) {
        return true;
    }
    return false;
}
项目:oma-riista-web    文件:ExternalMooseDataCardImportApiResource.java   
@CacheControl(policy = CachePolicy.NO_CACHE)
@RequestMapping(value = "/upload",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> importMooseDataCard(
        @RequestParam final multipartfile xmlFile,@RequestParam final multipartfile pdfFile) {

    LOG.debug("Moose data card upload request received via anonymous API");

    final SecurityContext sc = SecurityContextHolder.getContext();

    sc.setAuthentication(new AnonymousAuthenticationToken(
            "key",AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")));

    if (LOG.isDebugEnabled()) {
        LOG.debug("Populated SecurityContextHolder with anonymous token: '" + sc.getAuthentication() + "'");
    }

    try {
        return ResponseEntity.ok(toMap(importFeature.importMooseDataCardWithSpecialPrivilege(xmlFile,pdfFile)));
    } catch (final MooseDataCardImportException e) {
        return ResponseEntity.badRequest().body(toMap(e.getMessages()));
    }
}
项目:web-ui    文件:UserController.java   
@RequestMapping(value = "/",method = RequestMethod.GET)
public String showHome(Model model) {
    if (!model.containsAttribute("login")) {
        model.addAttribute("login",new AuthenticationRequest());
    }
    model.addAttribute("marketSummary",summaryService.getMarketSummary());

    //check if user is logged in!
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (!(authentication instanceof AnonymousAuthenticationToken)) {
        String currentUserName = authentication.getName();
        logger.debug("User logged in: " + currentUserName);

        try {
            model.addAttribute("accounts",accountService.getAccounts(currentUserName));
            model.addAttribute("portfolio",portfolioService.getPortfolio(currentUserName));
        } catch (HttpServerErrorException e) {
            model.addAttribute("portfolioRetrievalError",e.getMessage());
        }
        User user = userService.getUser(currentUserName);
        model.addAttribute("user",user);
        model.addAttribute("accounts",accountService.getAccounts(currentUserName));
    }

    return "index";
}
项目:web-ui    文件:AccountsController.java   
@RequestMapping(value = "/accounts",method = RequestMethod.GET)
public String accounts(Model model) {
    logger.debug("/accounts");
    model.addAttribute("marketSummary",summaryService.getMarketSummary());

    //check if user is logged in!
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (!(authentication instanceof AnonymousAuthenticationToken)) {
        String currentUserName = authentication.getName();
        logger.debug("accounts: User logged in: " + currentUserName);

        try {
            model.addAttribute("accounts",accountService.getAccounts(currentUserName));
        } catch (HttpServerErrorException e) {
            logger.debug("error retrieving accounts: " + e.getMessage());
            model.addAttribute("accountsRetrievalError",e.getMessage());
        }
    }

    return "accounts";
}
项目:web-ui    文件:TradeController.java   
@RequestMapping(value = "/Trade",method = RequestMethod.GET)
public String showTrade(Model model) {
    logger.debug("/Trade.GET");
    //model.addAttribute("marketSummary",marketService.getMarketSummary());

    model.addAttribute("search",new Search());
    //check if user is logged in!
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (!(authentication instanceof AnonymousAuthenticationToken)) {
        String currentUserName = authentication.getName();
        logger.debug("User logged in: " + currentUserName);
        model.addAttribute("order",new Order());

        try {
            model.addAttribute("portfolio",portfolioService.getPortfolio(currentUserName));
            model.addAttribute("accounts",accountService.getAccounts(currentUserName));
        } catch (HttpServerErrorException e) {
            model.addAttribute("portfolioRetrievalError",e.getMessage());
        }
    }

    return "Trade";
}
项目:web-ui    文件:PortfolioController.java   
@RequestMapping(value = "/portfolio",method = RequestMethod.GET)
public String portfolio(Model model) {
    logger.debug("/portfolio");
    model.addAttribute("marketSummary",summaryService.getMarketSummary());

    //check if user is logged in!
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (!(authentication instanceof AnonymousAuthenticationToken)) {
        String currentUserName = authentication.getName();
        logger.debug("portfolio: User logged in: " + currentUserName);

        //Todo: add account summary.
        try {
            model.addAttribute("portfolio",accountService.getAccounts(currentUserName));
        } catch (HttpServerErrorException e) {
            logger.debug("error retrieving portfolfio: " + e.getMessage());
            model.addAttribute("portfolioRetrievalError",e.getMessage());
        }
        model.addAttribute("order",new Order());
    }

    return "portfolio";
}
项目:fiat    文件:FiatAuthenticationFilter.java   
@Override
public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException,servletexception {
  Authentication auth = AuthenticatedRequest
      .getSpinnakerUser()
      .map(username -> (Authentication) new PreAuthenticatedAuthenticationToken(username,null,new ArrayList<>()))
      .orElseGet(() -> new AnonymousAuthenticationToken(
          "anonymous","anonymous",AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")
      ));

  val ctx = SecurityContextHolder.createEmptyContext();
  ctx.setAuthentication(auth);
  SecurityContextHolder.setContext(ctx);
  log.debug("Set SecurityContext to user: {}",auth.getPrincipal().toString());
  chain.doFilter(request,response);
}
项目:spring-tsers-auth    文件:SSOController.java   
@RequestMapping(value = "/idpSelection",method = RequestMethod.GET)
public String idpSelection(HttpServletRequest request,Model model) {
    if (!(SecurityContextHolder.getContext().getAuthentication() instanceof AnonymousAuthenticationToken)) {
        LOG.warn("The current user is already logged.");
        return "redirect:/landing";
    } else {
        if (isForwarded(request)) {
            Set<String> idps = Metadata.getIDPEntityNames();
            for (String idp : idps)
                LOG.info("Configured Identity Provider for SSO: " + idp);
            model.addAttribute("idps",idps);
            return "saml/idpselection";
        } else {
            LOG.warn("Direct accesses to '/idpSelection' route are not allowed");
            return "redirect:/";
        }
    }
}
项目:helicalinsight    文件:AdminController.java   
private String whenUserHasValidSession(Authentication authentication,HttpSession session) {
    String redirectUrl = null;
    if (!(authentication instanceof AnonymousAuthenticationToken)) {
        List<String> userRoles = AuthenticationUtils.getUserRoles();
        if (userRoles.contains(this.namesConfigurer.getRoleAdmin())) {
            String roleAdmin = namesConfigurer.getRoleAdmin();
            session.setAttribute("superAdminRole",roleService.findRoleByName(roleAdmin));
            redirectUrl = "./admin.html";
        } else if (userRoles.contains(this.namesConfigurer.getRoleUser())) {
            redirectUrl = "./hi.html";
        } else {
            redirectUrl = "./welcome.html";
        }
    }
    return redirectUrl;
}
项目:engerek    文件:MidpointRestSecurityQuestionsAuthenticator.java   
private List<SecurityQuestionDeFinitionType> getQuestions(PrismObject<UserType> user) {
    return getSecurityEnforcer().runPrivileged(new Producer<List<SecurityQuestionDeFinitionType>>() {

        @Override
        public List<SecurityQuestionDeFinitionType> run() {
            Task task = getTaskManager().createTaskInstance("Search user by name");
            OperationResult result = task.getResult();
            SecurityPolicyType securityPolicyType = null;
            try {
                SecurityContextHolder.getContext().setAuthentication(new AnonymousAuthenticationToken("rest_sec_q_auth","REST",AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")));
                securityPolicyType = modelInteractionService.getSecurityPolicy(user,task,result);
            } catch (ObjectNotFoundException | SchemaException e) {
                return null;
            } finally {
                SecurityContextHolder.getContext().setAuthentication(null);
            }
            if (securityPolicyType.getCredentials() != null && securityPolicyType.getCredentials().getSecurityQuestions() != null){
                return securityPolicyType.getCredentials().getSecurityQuestions().getQuestion();
            }
            return null;
        }
    });

}
项目:springBootTrader-aos    文件:UserController.java   
@RequestMapping(value = "/",marketService.getMarketSummary());

    //check if user is logged in!
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (!(authentication instanceof AnonymousAuthenticationToken)) {
        String currentUserName = authentication.getName();
        logger.debug("User logged in: " + currentUserName);

        try {
            model.addAttribute("portfolio",marketService.getPortfolio(currentUserName));
        } catch (HttpServerErrorException e) {
            model.addAttribute("portfolioRetrievalError",e.getMessage());
        }
        model.addAttribute("account",accountService.getAccount(currentUserName));
    }

    return "index";
}
项目:springBootTrader-aos    文件:TradeController.java   
@RequestMapping(value = "/Trade",new Order());
        //Todo: add account summary?
        try {
            model.addAttribute("portfolio",e.getMessage());
        }
    }

    return "Trade";
}
项目:springBootTrader-aos    文件:TradeController.java   
@RequestMapping(value = "/order",method = RequestMethod.POST)
public String buy(Model model,@modelattribute("order") Order order) {
    model.addAttribute("search",new Search());

    // buy the order after setting attributes not set by the UI.
    //check if user is logged in!
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (!(authentication instanceof AnonymousAuthenticationToken)) {
                String currentUserName = authentication.getName();
                logger.debug("/order ORDER: " + order);
                order.setAccountId(currentUserName);
                order.setCompletionDate(new Date());

                Order result = marketService.sendOrder(order);
                model.addAttribute("savedOrder",result);
                model.addAttribute("order",new Order());
                try {
                    model.addAttribute("portfolio",marketService.getPortfolio(currentUserName));
                } catch (HttpServerErrorException e) {
                    model.addAttribute("portfolioRetrievalError",e.getMessage());
                }
            } else {
                //should never get here!!!
            }
    return "Trade";
}
项目:springBootTrader-aos    文件:PortfolioController.java   
@RequestMapping(value = "/portfolio",marketService.getMarketSummary());

    //check if user is logged in!
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (!(authentication instanceof AnonymousAuthenticationToken)) {
        String currentUserName = authentication.getName();
        logger.debug("portfolio: User logged in: " + currentUserName);

        //Todo: add account summary.
        try {
            model.addAttribute("portfolio",marketService.getPortfolio(currentUserName));
        } catch (HttpServerErrorException e) {
            logger.debug("error retrieving portfolfio: " + e.getMessage());
            model.addAttribute("portfolioRetrievalError",new Order());
    }

    return "portfolio";
}
项目:NetLicensing-Gateway    文件:SecurityHelper.java   
public Context getContext() {
    final Context context = new Context();
    context.setBaseUrl(nlicBaseUrl);
    context.setSecurityMode(SecurityMode.BASIC_AUTHENTICATION);
    context.setobject(RestProvider.Configuration.class,new GWClientConfiguration());

    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null) {
        if (authentication instanceof AnonymousAuthenticationToken) {
            // Todo(2K): handle missing authentication (no cases so far)
            context.setUsername("");
            context.setPassword("");
        } else {
            context.setUsername(authentication.getPrincipal().toString());
            context.setPassword(authentication.getCredentials().toString());
        }
    }
    return context;
}
项目:java-spring-jspx-hibernate-template    文件:RootController.java   
@RequestMapping(value = Constants.Url.LOGIN,method = RequestMethod.GET)
public String showLoginPage(@RequestParam(value = Constants.RequestParam.ERROR,required = false) Boolean error,@RequestParam(value = Constants.RequestParam.logoUT,required = false) Boolean logout,Model model) {
    SecurityContext securityContext = SecurityContextHolder.getContext();
    if (securityContext != null) {
        Authentication authentication = securityContext.getAuthentication();
        if (authentication != null && !(authentication instanceof AnonymousAuthenticationToken)) {
            return Constants.Url.REDIRECT + Constants.Url.ROOT;
        }
    }
    if (error != null) {
        model.addAttribute(Constants.modelattribute.ERROR,Constants.Messages.PAGE_LOGIN_ERROR_INVALID_USERNAME_AND_PASSWORD);
    }
    if (logout != null) {
        model.addAttribute(Constants.modelattribute.logoUT,Constants.Messages.PAGE_LOGIN_MESSAGE_logoUT);
    }
    return Constants.View.LOGIN;
}
项目:owsi-core-parent    文件:AbstractCoreSession.java   
/**
 * @see AbstractCoreSession#authenticate(String,String)
 */
public void signInAs(String username) throws UsernameNotFoundException {
    // on charge l'utilisateur
    // on le passe dans une méthode surchargeable -> implémentation par défaut à faire
    // Sitra -> revoir l'implémentation par défaut
    if (!hasSignInAsPermissions(getUser(),userService.getByUserName(username))) {
        throw new SecurityException("L'utilisateur n'a pas les permissions nécessaires");
    }
    UserDetails userDetails = userDetailsService.loadUserByUsername(username);
    RunAsUserToken token = new RunAsUserToken(defaultJpaSecurityConfig.getRunAsKey(),userDetails,"runAs",userDetails.getAuthorities(),null);

    // On garde l'authentification de l'utilisateur pour pouvoir lui proposer de se reconnecter.
    Authentication prevIoUsAuthentication = SecurityContextHolder.getContext().getAuthentication();
    if (!(prevIoUsAuthentication instanceof AnonymousAuthenticationToken)) {
        originalAuthentication = prevIoUsAuthentication;
    }

    signOut();

    Authentication authentication = authenticationManager.authenticate(token);
    SecurityContextHolder.getContext().setAuthentication(authentication);
    doInitializeSession();
    bind();
    signIn(true);
}
项目:data-acquisition    文件:PermissionAcquireFilter.java   
@Override protected void doFilterInternal(HttpServletRequest request,HttpServletResponse httpServletResponse,FilterChain filterChain)
    throws servletexception,IOException {
    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    String authHeader = null;
    if(authentication != null && !(authentication instanceof AnonymousAuthenticationToken)) {
        authHeader = tokenRetriever.getAuthToken(authentication);
    }

    if(authHeader == null) {
        LOGGER.debug("Request has no authorization header.");
        httpServletResponse.sendError(401,"Unauthorized.");
    }
    else {
        UUID[] ids = authorization.getAccessibleOrgs(request).stream()
                .map(org -> org.getorganization().getGuid()).toArray(size -> new UUID[size]);
        request.setAttribute(ACCESSIBLE_ORGS,ids);

        if (ids.length > 0) {
            filterChain.doFilter(request,httpServletResponse);
        } else {
            LOGGER.debug("User access denied.");
            httpServletResponse.sendError(403,"Can't access this organization.");
        }
    }
}
项目:hotel_shop    文件:MainController.java   
/**
 * Accesss denied.
 *
 * @return the model and view
 */
@RequestMapping(value = "/403",method = RequestMethod.GET)
public ModelAndView accesssDenied(HttpServletRequest request) {
    ModelAndView model = new ModelAndView();

    // check if user is login
    Authentication auth = SecurityContextHolder.getContext()
            .getAuthentication();
    if (!(auth instanceof AnonymousAuthenticationToken)) {
        UserDetails userDetail = (UserDetails) auth.getPrincipal();
        System.out.println(userDetail);

        model.addobject("username",userDetail.getUsername());

    }

    model.setViewName(checkName("403",request));
    return model;

}
项目:hotel_shop    文件:MainController.java   
/**
 * Not found.
 *
 * @return the model and view
 */
@RequestMapping(value = "/404",method = RequestMethod.GET)
public ModelAndView notFound(HttpServletRequest request) {

    ModelAndView model = new ModelAndView();

    // check if user is login
    Authentication auth = SecurityContextHolder.getContext()
            .getAuthentication();
    if (!(auth instanceof AnonymousAuthenticationToken)) {
        UserDetails userDetail = (UserDetails) auth.getPrincipal();
        System.out.println(userDetail);

        model.addobject("username",userDetail.getUsername());

    }

    model.setViewName(checkName("404",request));
    return model;

}
项目:webanno    文件:LoginPage.java   
private void redirectIfAlreadyLoggedIn()
{
    // If we are already logged in,redirect to the welcome page. This tries to a void a
    // situation where the user tries to access the login page directly and thus the
    // application would redirect the user to the login page after a successful login
    if (!(SecurityContextHolder.getContext()
            .getAuthentication() instanceof AnonymousAuthenticationToken)) {
        log.debug("Already logged in,forwarding to home page");
        throw new RestartResponseException(getApplication().getHomePage());
    }

    String redirectUrl = getRedirectUrl();
    if (redirectUrl == null) {
        log.debug("Authentication required");
    }
    else {
        log.debug("Authentication required (original URL: [{}])",redirectUrl);
    }
}
项目:workbenchauth    文件:HomeController.java   
@RequestMapping(value = "/403",method = RequestMethod.GET)
public ModelAndView accesssDenied() {

  final ModelAndView model = new ModelAndView();

  // check if user is login
  final Authentication auth = SecurityContextHolder.getContext()
      .getAuthentication();
  if (!(auth instanceof AnonymousAuthenticationToken)) {
    final UserDetails userDetail = (UserDetails) auth.getPrincipal();
    model.addobject("username",userDetail.getUsername());
  }

  model.setViewName("403");
  return model;

}
项目:eds-starter6-jpa    文件:AppLocaleResolver.java   
@Override
public Locale resolveLocale(HttpServletRequest request) {
    Authentication authentication = SecurityContextHolder.getContext()
            .getAuthentication();
    if (authentication == null
            || authentication instanceof AnonymousAuthenticationToken) {
        return request.getLocale();
    }
    else if (authentication.getPrincipal() instanceof JpaUserDetails) {
        return ((JpaUserDetails) authentication.getPrincipal()).getLocale();
    }
    else if (getDefaultLocale() != null) {
        return getDefaultLocale();
    }
    else {
        return Locale.ENGLISH;
    }
}
项目:cf-SpringBootTrader    文件:UserController.java   
@RequestMapping(value = "/",summaryService.getMarketSummary());

    //check if user is logged in!
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (!(authentication instanceof AnonymousAuthenticationToken)) {
        String currentUserName = authentication.getName();
        logger.debug("User logged in: " + currentUserName);

        try {
            model.addAttribute("portfolio",accountService.getAccount(currentUserName));
    }

    return "index";
}
项目:cf-SpringBootTrader    文件:TradeController.java   
@RequestMapping(value = "/Trade",method = RequestMethod.GET)
public String showTrade(Model model) {
    logger.debug("/Trade.GET");

    model.addAttribute("search",e.getMessage());
        }
    }

    return "Trade";
}
项目:cf-SpringBootTrader    文件:TradeController.java   
@RequestMapping(value = "/order",e.getMessage());
                }
            } else {
                //should never get here!!!
            }
    return "Trade";
}
项目:cf-SpringBootTrader    文件:PortfolioController.java   
@RequestMapping(value = "/portfolio",new Order());
    }

    return "portfolio";
}
项目:eds-starter6-mongodb    文件:AppLocaleResolver.java   
@Override
public Locale resolveLocale(HttpServletRequest request) {
    Authentication authentication = SecurityContextHolder.getContext()
            .getAuthentication();
    if (authentication == null
            || authentication instanceof AnonymousAuthenticationToken) {
        return request.getLocale();
    }
    else if (authentication.getPrincipal() instanceof MongoUserDetails) {
        return ((MongoUserDetails) authentication.getPrincipal()).getLocale();
    }
    else if (getDefaultLocale() != null) {
        return getDefaultLocale();
    }
    else {
        return Locale.ENGLISH;
    }
}
项目:swagger-cxf-rest-skeleton    文件:LoginAuthenticationSuccessHandler.java   
@Override
public void onAuthenticationSuccess(final HttpServletRequest request,final HttpServletResponse response,final Authentication authentication) throws IOException,servletexception {

    if (!(authentication instanceof AnonymousAuthenticationToken)) {
        final UserDetails userDetails = (UserDetails) authentication.getPrincipal();

        final String token = authenticationTokenService.generateAuthenticationToken(userDetails.getUsername());

        final Cookie cookie = new Cookie("api_token",token);
        cookie.setHttpOnly(true);
        cookie.setPath("/");
        response.addCookie(cookie);

        response.setStatus(HttpServletResponse.SC_OK);
    }
}
项目:cosmo    文件:CosmoSecurityContextImpl.java   
protected void processprincipal() {  
    //anonymous principals do not have CosmoUserDetails and by
    //deFinition are not running as other principals
    if (getPrincipal() instanceof AnonymousAuthenticationToken) {
        setAnonymous(true);
    } else if (getPrincipal() instanceof UsernamePasswordAuthenticationToken) {
        CosmoUserDetails details = (CosmoUserDetails)
            ((Authentication) getPrincipal()).getPrincipal();
        setUser(details.getUser());
        setAdmin(details.getUser().getAdmin().booleanValue());
    } else if (getPrincipal() instanceof TicketAuthenticationToken) {
        Ticket ticket = (Ticket)((Authentication) getPrincipal()).getPrincipal();
        setTicket(ticket);
    } else {
        throw new CosmoException("UnkNown principal type " + getPrincipal().getClass().getName(),new CosmoException());
    }
}
项目:midpoint    文件:MidpointRestSecurityQuestionsAuthenticator.java   
private List<SecurityQuestionDeFinitionType> getQuestions(PrismObject<UserType> user) {
    return getSecurityContextManager().runPrivileged(new Producer<List<SecurityQuestionDeFinitionType>>() {

        @Override
        public List<SecurityQuestionDeFinitionType> run() {
            Task task = getTaskManager().createTaskInstance("Search user by name");
            OperationResult result = task.getResult();
            SecurityPolicyType securityPolicyType = null;
            try {
                SecurityContextHolder.getContext().setAuthentication(new AnonymousAuthenticationToken("rest_sec_q_auth",result);
            } catch (ObjectNotFoundException | SchemaException e) {
                return null;
            } finally {
                SecurityContextHolder.getContext().setAuthentication(null);
            }
            if (securityPolicyType.getCredentials() != null && securityPolicyType.getCredentials().getSecurityQuestions() != null){
                return securityPolicyType.getCredentials().getSecurityQuestions().getQuestion();
            }
            return null;
        }
    });

}
项目:spring-boot-security-saml-sample    文件:SSOController.java   
@RequestMapping(value = "/idpSelection",idps);
            return "saml/idpselection";
        } else {
            LOG.warn("Direct accesses to '/idpSelection' route are not allowed");
            return "redirect:/";
        }
    }
}
项目:spring-boot-security-saml-sample    文件:CommonTestSupport.java   
public MockHttpSession mockAnonymousHttpSession() {
    MockHttpSession mockSession = new MockHttpSession();

    SecurityContext mockSecurityContext = mock(SecurityContext.class);

    AnonymousAuthenticationToken principal =
            new AnonymousAuthenticationToken(
                    ANONYMOUS_USER_KEY,ANONYMOUS_USER_PRINCIPAL,AUTHORITIES);

    when(mockSecurityContext.getAuthentication()).thenReturn(principal);

    SecurityContextHolder.setContext(mockSecurityContext);
    mockSession.setAttribute(
            HttpSessionSecurityContextRepository.SPRING_Security_CONTEXT_KEY,mockSecurityContext);

    return mockSession;
}

org.springframework.security.authentication.AuthenticationCredentialsNotFoundException的实例源码

org.springframework.security.authentication.AuthenticationCredentialsNotFoundException的实例源码

项目:AngularandSpring    文件:MyAuthenticationProvider.java   
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String name = authentication.getName();
    String password = authentication.getCredentials().toString();       
    Query query = new Query();
    query.addCriteria(Criteria.where("userId").is(name));
    MyUser user = operations.findOne(query,MyUser.class).block();
    String encryptedPw = null;
    try {
        encryptedPw = this.passwordEncryption.getEncryptedPassword(password,user.getSalt());
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
        log.error("Pw decrytion error: ",e);
    }
    if(encryptedPw == null || !encryptedPw.equals(user.getpassword())) {
        throw new AuthenticationCredentialsNotFoundException("User: "+name+" not found.");
    }
    log.info("User: "+name+" logged in.");
    return new UsernamePasswordAuthenticationToken(
            name,password,user.getAuthorities());
}
项目:joal    文件:WebSocketAuthenticatorService.java   
public UsernamePasswordAuthenticationToken getAuthenticatedOrFail(final CharSequence username,final CharSequence authToken) throws AuthenticationException {
    if (StringUtils.isBlank(username)) {
        throw new AuthenticationCredentialsNotFoundException("Username was null or empty.");
    }
    if (StringUtils.isBlank(authToken)) {
        throw new AuthenticationCredentialsNotFoundException("Authentication token was null or empty.");
    }
    if (!appSecretToken.equals(authToken)) {
        throw new BadCredentialsException("Authentication token does not match the expected token");
    }

    // Everithing is fine,return an authenticated Authentication. (the constructor with grantedAuthorities auto set authenticated = true)
    // null credentials,we do not pass the password along to prevent security flaw
    return new UsernamePasswordAuthenticationToken(
            username,null,Collections.singleton((GrantedAuthority) () -> "USER")
    );
}
项目:OpenLRW    文件:AjaxAuthenticationProvider.java   
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    Assert.notNull(authentication,"No authentication data provided");

    String key = (String) authentication.getPrincipal();
    String secret = (String) authentication.getCredentials();

    Org org;
    try {
      org = orgService.findByApiKeyAndApiSecret(key,secret);
    } 
    catch (OrgNotFoundException e) {
      throw new AuthenticationCredentialsNotFoundException(e.getMessage());
    }
    List<GrantedAuthority> authorities = Collections.singletonList(new SimpleGrantedAuthority("ROLE_ORG_ADMIN"));        
    UserContext userContext = UserContext.create(org.getMetadata().get(Vocabulary.TENANT),org.getSourcedId(),authorities);        
    return new UsernamePasswordAuthenticationToken(userContext,userContext.getAuthorities());
}
项目:item-shop-reactive-backend    文件:AuthorizationWebFilter.java   
@Override
public Mono<Void> filter(ServerWebExchange exchange,WebFilterChain chain) {
    return exchange.getPrincipal()
        .filter(p -> p instanceof Authentication)
        .then( p-> Mono.just((Authentication) p))
        .filter(authentication -> {
            return authentication != null && authentication.isAuthenticated();
        })
        .then(authentication -> {
            return source.getConfigAttributes(exchange).as( (Function<? super Flux<ConfigAttribute>,Mono<Boolean>>) a -> {
                return accessDecisionManager.decide(authentication,exchange,a);
            });
        })
        .filter(t -> t)
        .otherwiseIfEmpty(Mono.defer(() -> {
            return entryPoint.commence(exchange,new AuthenticationCredentialsNotFoundException("Not Found"));
        }))
        .then(sc -> {
            return chain.filter(exchange);
        });
}
项目:secrets-proxy    文件:JwtTokenService.java   
/**
 * Retrieves the JWT authentication token from http request.
 *
 * @param req http request.
 * @return {@link JwtAuthToken} or <code>null</code> if the Bearer token is not present or empty.
 */
public @Nullable
JwtAuthToken getAccesstoken(@Nonnull HttpServletRequest req) {
    log.debug("Getting the access token for " + req.getRequestURI());

    String bearerToken = req.getHeader(tokenHeader);
    if (bearerToken != null) {
        // Make sure it's valid token type.
        if (!bearerToken.startsWith(tokenType)) {
            throw new AuthenticationCredentialsNotFoundException("Invalid Authorization Token.");
        }

        String jwtToken = bearerToken.replaceFirst(tokenType,"").trim();
        if (!isEmpty(jwtToken)) {
            return new JwtAuthToken("JwtToken",jwtToken,Collections.emptyList());
        }
    }

    log.debug("JWT Bearer token is null/empty for " + req.getRequestURI());
    return null;
}
项目:spring-security-reactive    文件:AuthorizationWebFilter.java   
@Override
public Mono<Void> filter(ServerWebExchange exchange,WebFilterChain chain) {
    return exchange.getPrincipal()
        .filter(p -> p instanceof Authentication)
        .flatMap( p-> Mono.just((Authentication) p))
        .filter(authentication -> {
            return authentication != null && authentication.isAuthenticated();
        })
        .flatMap(authentication -> {
            return source.getConfigAttributes(exchange).as( (Function<? super Flux<ConfigAttribute>,a);
            });
        })
        .filter(t -> t)
        .switchIfEmpty(Mono.defer(() -> {
            return entryPoint.commence(exchange,new AuthenticationCredentialsNotFoundException("Not Found"));
        }))
        .flatMap(sc -> {
            return chain.filter(exchange);
        });
}
项目:engerek    文件:AuthenticationEvaluatorImpl.java   
@Override
public UsernamePasswordAuthenticationToken authenticate(ConnectionEnvironment connEnv,T authnCtx) 
        throws BadCredentialsException,AuthenticationCredentialsNotFoundException,disabledException,LockedException,CredentialsExpiredException,AuthenticationServiceException,AccessDeniedException,UsernameNotFoundException {     

    checkEnteredCredentials(connEnv,authnCtx);

    MidPointPrincipal principal = getAndCheckPrincipal(connEnv,authnCtx.getUsername(),true);

    UserType userType = principal.getUser();
    CredentialsType credentials = userType.getCredentials();
    CredentialPolicyType credentialsPolicy = getCredentialsPolicy(principal,authnCtx);

    if (checkCredentials(principal,authnCtx,connEnv)) {

        recordPasswordAuthenticationSuccess(principal,connEnv,getCredential(credentials),credentialsPolicy);
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(principal,authnCtx.getEnteredCredential(),principal.getAuthorities());
        return token;

    } else {
        recordPasswordAuthenticationFailure(principal,credentialsPolicy,"password mismatch");

        throw new BadCredentialsException("web.security.provider.invalid");
    }
}
项目:engerek    文件:AuthenticationEvaluatorImpl.java   
@Override
public UserType checkCredentials(ConnectionEnvironment connEnv,false);

    UserType userType = principal.getUser();
    CredentialsType credentials = userType.getCredentials();
    CredentialPolicyType credentialsPolicy = getCredentialsPolicy(principal,connEnv)) {
        return userType;
    } else {
        recordPasswordAuthenticationFailure(principal,"password mismatch");

        throw new BadCredentialsException("web.security.provider.invalid");
    }
}
项目:engerek    文件:AuthenticationEvaluatorImpl.java   
private <P extends CredentialPolicyType> void checkPasswordValidityAndAge(ConnectionEnvironment connEnv,@NotNull MidPointPrincipal principal,C credentials,P passwordCredentialsPolicy) {
    if (credentials == null) {
        recordAuthenticationFailure(principal,"no stored credential value");
        throw new AuthenticationCredentialsNotFoundException("web.security.provider.credential.bad");
    }

    validateCredentialNotNull(connEnv,principal,credentials);

    if (passwordCredentialsPolicy == null) {
        return;
    }

    Duration maxAge = passwordCredentialsPolicy.getMaxAge();
    if (maxAge != null) {
        MetadataType credentialMetedata = credentials.getMetadata();
        XMLGregorianCalendar changeTimestamp = MiscSchemaUtil.getChangeTimestamp(credentialMetedata);
        if (changeTimestamp != null) {
            XMLGregorianCalendar passwordValidUntil = XmlTypeConverter.addDuration(changeTimestamp,maxAge);
            if (clock.isPast(passwordValidUntil)) {
                recordAuthenticationFailure(principal,"password expired");
                throw new CredentialsExpiredException("web.security.provider.password.bad");
            }
        }
    }
}
项目:engerek    文件:AuthenticationEvaluatorImpl.java   
private void checkPasswordValidityAndAge(ConnectionEnvironment connEnv,ProtectedStringType protectedString,MetadataType passwordMetadata,CredentialPolicyType passwordCredentialsPolicy) {
    if (protectedString == null) {
        recordAuthenticationFailure(principal,"no stored password value");
        throw new AuthenticationCredentialsNotFoundException("web.security.provider.password.bad");
    }
    if (passwordCredentialsPolicy == null) {
        return;
    }
    Duration maxAge = passwordCredentialsPolicy.getMaxAge();
    if (maxAge != null) {
        XMLGregorianCalendar changeTimestamp = MiscSchemaUtil.getChangeTimestamp(passwordMetadata);
        if (changeTimestamp != null) {
            XMLGregorianCalendar passwordValidUntil = XmlTypeConverter.addDuration(changeTimestamp,"password expired");
                throw new CredentialsExpiredException("web.security.provider.password.bad");
            }
        }
    }
}
项目:cibet    文件:SpringSecurityActuator.java   
private Authentication swapAuthentication() {
   if (secondPrincipal) {
      Object secP = Context.internalSessionScope().getProperty(InternalSessionScope.SECOND_PRINCIPAL);
      if (secP == null) {
         throw new AuthenticationCredentialsNotFoundException(
               "No Authentication object found in CibetContext.getSecondPrincipal()");
      }

      if (!(secP instanceof Authentication)) {
         throw new AccessDeniedException("CibetContext.getSecondPrincipal() is expected to be of type "
               + Authentication.class.getName() + " but is of type " + secP.getClass().getName());
      }

      log.debug("SpringSecurity actuator for second principal " + secP);
      Authentication auth = (Authentication) secP;
      Authentication original = SecurityContextHolder.getContext().getAuthentication();
      SecurityContextHolder.getContext().setAuthentication(auth);
      return original;
   }
   return null;
}
项目:Open-Clinica-Data-Uploader    文件:ListStudiesResponseHandler.java   
public static List<Study> parseListStudiesResponse(SOAPMessage response) throws Exception { //Todo: handle exception
    Document document = todocument(response);
    String result = isAuthFailure(document);
    if (! StringUtils.isEmpty(result)) {
        throw new AuthenticationCredentialsNotFoundException("Problem calling OpenClinica web-services: " + result);
    }
    XPath xpath = XPathFactory.newInstance().newXPath();
    NodeList studyNodes = (NodeList) xpath.evaluate("//listAllResponse/studies/study",document,XPathConstants.NODESET);
    List<Study> studiesParsed = new ArrayList<>();
    for (int i = 0; i < studyNodes.getLength(); i++) {
        Node studyNode = studyNodes.item(i);
        Study study = parseStudy(studyNode);
        studiesParsed.add(study);
    }
    return studiesParsed;
}
项目:Open-Clinica-Data-Uploader    文件:SOAPResponseHandler.java   
/**
 * Checks if an error occurred on the OpenClinica-side and reports it back as the
 * return value
 *
 * @param response the SOAP-response.
 * @return a non <code>null</code> error code.message if an error occurred. Some are reported by the OpenClinica-WS
 * instance at url. Returns <code>null</code> if everything went OK.
 * @throws Exception if a technical error occurs.
 */

public static String parSEOpenClinicaResponse(SOAPMessage response,String xPathToResponse) throws Exception {
    Document document = todocument(response);
    System.out.println("SOAP:----->\n" + SoapUtils.soapMessagetoString(response));
    String result = isAuthFailure(document);
    if (! StringUtils.isEmpty(result)) {
        throw new AuthenticationCredentialsNotFoundException("Problem calling OpenClinica web-services: " + result);
    }
    XPath xpath = XPathFactory.newInstance().newXPath();
    Node importDataResponseNode = (Node) xpath.evaluate(xPathToResponse,XPathConstants.NODE);
    Node resultNode = (Node) xpath.evaluate("//result",importDataResponseNode,XPathConstants.NODE);
    if ("fail".equalsIgnoreCase(resultNode.getTextContent())) {
        Node errorNode = (Node) xpath.evaluate("//error",XPathConstants.NODE);
        return errorNode.getTextContent();
    }
    return null;
}
项目:Open-Clinica-Data-Uploader    文件:IsstudySubjectResponseHandler.java   
/**
 * Retrieve the study subjects technical ID; <code>studuSubjectOID</code> in OpenClinica
 * terminology.
 * @param response the SOAP-response
 * @return <code>null</code> if the provided subject label does not exist in the study otherwise
 * the <code>studySubjectOID</code>
 * @throws Exception on authentication failures or response structure mismatch
 */
public static String parseIsstudySubjectResponse(SOAPMessage response) throws Exception {
    if (response == null) {
        return null;
    }
    Document document = todocument(response);
    String result = isAuthFailure(document);
    if (! StringUtils.isEmpty(result)) {
        throw new AuthenticationCredentialsNotFoundException("Problem calling OpenClinica web-services: " + result);
    }
    XPath xpath = XPathFactory.newInstance().newXPath();
    Node createResponseNode = (Node) xpath.evaluate("//createResponse",createResponseNode,XPathConstants.NODE);
    if ("Success".equals(resultNode.getTextContent())) {
        Node subjectOIDNode = (Node) xpath.evaluate("//subjectOID",XPathConstants.NODE);
        if (subjectOIDNode != null) {
            return subjectOIDNode.getTextContent();
        }
        throw new IllegalStateException("SubjectOID node is null");
    }
    else {
        return null;
    }
}
项目:spring-json-sms-gateway    文件:SMS.java   
public SMS(JSON_SMS jsonSMS,int user_id) throws GatewayException {

        if (user_id < 1)
            throw new AuthenticationCredentialsNotFoundException("no user id on sms repository");

        this.id = jsonSMS.getId();
        this.user_id = user_id;
        this.sender = jsonSMS.getSender();
        this.msisdn = jsonSMS.getMsisdn();
        this.text = jsonSMS.getText();
        this.subid = jsonSMS.getSubid();
        this.ackurl = jsonSMS.getAck_url();
        this.datetimeScheduled = jsonSMS.getDatetime();
        this.test = jsonSMS.istest();

        if (datetimeScheduled != null)
            sms_status = SMS_Status.SCHEDULED;
        else
            sms_status = SMS_Status.ACCEPTD;

    }
项目:midpoint    文件:AuthenticationEvaluatorImpl.java   
@Override
public UsernamePasswordAuthenticationToken authenticate(ConnectionEnvironment connEnv,T authnCtx)
        throws BadCredentialsException,UsernameNotFoundException {

    checkEnteredCredentials(connEnv,"password mismatch");

        throw new BadCredentialsException("web.security.provider.invalid");
    }
}
项目:midpoint    文件:AuthenticationEvaluatorImpl.java   
@Override
public UserType checkCredentials(ConnectionEnvironment connEnv,"password mismatch");

        throw new BadCredentialsException("web.security.provider.invalid");
    }
}
项目:midpoint    文件:AuthenticationEvaluatorImpl.java   
private <P extends CredentialPolicyType> void checkPasswordValidityAndAge(ConnectionEnvironment connEnv,"password expired");
                throw new CredentialsExpiredException("web.security.provider.credential.expired");
            }
        }
    }
}
项目:midpoint    文件:AuthenticationEvaluatorImpl.java   
private void checkPasswordValidityAndAge(ConnectionEnvironment connEnv,"password expired");
                throw new CredentialsExpiredException("web.security.provider.credential.expired");
            }
        }
    }
}
项目:syncope    文件:AuthDataAccessor.java   
public JWTSSOProvider getJWTSSOProvider(final String issuer) {
    synchronized (this) {
        if (jwtSSOProviders == null) {
            jwtSSOProviders = new HashMap<>();

            implementationLookup.getJWTSSOProviderClasses().stream().
                    map(clazz -> (JWTSSOProvider) ApplicationContextProvider.getbeanfactory().
                    createBean(clazz,AbstractBeanDeFinition.AUTOWIRE_BY_TYPE,true)).
                    forEachOrdered(jwtSSOProvider -> {
                        jwtSSOProviders.put(jwtSSOProvider.getIssuer(),jwtSSOProvider);
                    });
        }
    }

    if (issuer == null) {
        throw new AuthenticationCredentialsNotFoundException("A null issuer is not permitted");
    }
    JWTSSOProvider provider = jwtSSOProviders.get(issuer);
    if (provider == null) {
        throw new AuthenticationCredentialsNotFoundException(
                "Could not find any registered JWTSSOProvider for issuer " + issuer);
    }

    return provider;
}
项目:vaadin4spring    文件:AbstractVaadinSecurityConfiguration.java   
@Bean(name = CURRENT_USER_BEAN)
Authentication currentUser() {

    return ProxyFactory.getProxy(Authentication.class,new MethodInterceptor() {

        @Override
        public Object invoke(MethodInvocation invocation) throws Throwable {
            SecurityContext securityContext = SecurityContextHolder.getContext();
            Authentication authentication = securityContext.getAuthentication();
            if (authentication == null) {
                throw new AuthenticationCredentialsNotFoundException("No authentication found in current security context");
            }
            return invocation.getmethod().invoke(authentication,invocation.getArguments());
        }

    });

}
项目:metka    文件:AuthenticationUtil.java   
public static boolean authenticate(MetkaAuthenticationDetails details) {
    SecurityContext context = SecurityContextHolder.getContext();
    if(context == null) {
        Logger.error(AuthenticationUtil.class,"Authentication was requested but no SecurityContext was found");
        throw new AuthenticationCredentialsNotFoundException("Couldn't find security context");
    }
    /*Authentication authentication = context.getAuthentication();
    if(authentication != null && authentication.getDetails() != null) {
        logger.error("Authentication details already set");
        throw new AuthenticationCredentialsNotFoundException("Authentication details already set");
    }*/
    PreAuthenticatedAuthenticationToken auth = new PreAuthenticatedAuthenticationToken(details.getUserName(),"credentials",details.getGrantedAuthorities());
    auth.setDetails(details);
    context.setAuthentication(auth);
    return true;
}
项目:metka    文件:AuthenticationUtil.java   
private static MetkaAuthenticationDetails getDetails() throws AuthenticationCredentialsNotFoundException {
    SecurityContext context = SecurityContextHolder.getContext();
    if(context == null) {
        Logger.error(AuthenticationUtil.class,"User name was requested but no SecurityContext was found");
        throw new AuthenticationCredentialsNotFoundException("Couldn't find security context");
    }
    Authentication authentication = context.getAuthentication();
    if(authentication == null) {
        Logger.error(AuthenticationUtil.class,"SecurityContext was found but no authentication details were set");
        throw new AuthenticationCredentialsNotFoundException("Couldn't find Authentication information");
    }
    if(authentication.getDetails() == null || !(authentication.getDetails() instanceof MetkaAuthenticationDetails)) {
        Logger.error(AuthenticationUtil.class,"Authentication details are null or don't match expected format");
        throw new AuthenticationCredentialsNotFoundException("Authentication details are null or not in expected format");
    }
    return (MetkaAuthenticationDetails)authentication.getDetails();
}
项目:spring-boot-start-current    文件:ContextUtils.java   
/**
 * 得到凭证
 */
private static Authentication getAuthentication () {
    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if ( Objects.isNull( authentication ) ) {
        throw new AuthenticationCredentialsNotFoundException( "未授权" );
    }
    return authentication;
}
项目:spring-boot-start-current    文件:AuthenticationController.java   
/**
 * 刷新并认证token
 *
 * @return token
 */
@PutMapping
public ResponseEntity refreshAndGetAuthenticationToken ( @RequestHeader( "${jwt.header:Authorization}" ) final String token ) {
    String username = jwtTokenUtil.getUsernameFromToken( token );
    if ( StringUtils.isBlank( username ) ) {
        throw new AuthenticationCredentialsNotFoundException( "无效token" );
    }
    JwtUser user = ( JwtUser ) userDetailsService.loadUserByUsername( username );
    if ( jwtTokenUtil.canTokenBeRefreshed( token,user.getLastPasswordResetDate() ) ) {
        String refreshedToken = jwtTokenUtil.refreshToken( token );
        return new ResponseEntityPro().add( "token",refreshedToken ).buildOk();
    } else {
        return ResponseEntityPro.badRequest( "原 token 无效" );
    }
}
项目:nifi-registry    文件:AuthenticationCredentialsNotFoundExceptionMapper.java   
@Override
public Response toResponse(AuthenticationCredentialsNotFoundException exception) {
    // log the error
    logger.info(String.format("No valid credentials were found in the request: %s. Returning %s response.",exception,Response.Status.FORBIDDEN));

    if (logger.isDebugEnabled()) {
        logger.debug(StringUtils.EMPTY,exception);
    }

    return Response.status(Response.Status.FORBIDDEN).entity("Access is denied.").type("text/plain").build();
}
项目:secrets-proxy    文件:TokenAuthProcessingFilter.java   
@Override
public Authentication attemptAuthentication(HttpServletRequest req,HttpServletResponse res) throws AuthenticationException,IOException,servletexception {
    log.debug("Attempting token authentication.");
    JwtAuthToken jwtAuthToken = jwtTokenService.getAccesstoken(req);
    if (jwtAuthToken == null) {
        throw new AuthenticationCredentialsNotFoundException("Authorization header is missing.");
    }
    return getAuthenticationManager().authenticate(jwtAuthToken);
}
项目:engerek    文件:SecurityQuestionAuthneticationEvaluatorImpl.java   
@Override
protected void validateCredentialNotNull(ConnectionEnvironment connEnv,MidPointPrincipal principal,SecurityQuestionsCredentialsType credential) {
    List<SecurityQuestionAnswerType> securityQuestionsAnswers = credential.getQuestionAnswer();

    if (securityQuestionsAnswers == null || securityQuestionsAnswers.isEmpty()) {
        recordAuthenticationFailure(principal,"no stored security questions");
        throw new AuthenticationCredentialsNotFoundException("web.security.provider.password.bad");
    }

}
项目:engerek    文件:NonceAuthenticationEvaluatorImpl.java   
@Override
protected void validateCredentialNotNull(ConnectionEnvironment connEnv,NonceType credential) {
    if (credential.getValue() == null) {
        recordAuthenticationFailure(principal,"no stored password value");
        throw new AuthenticationCredentialsNotFoundException("web.security.provider.password.bad");
    }

}
项目:engerek    文件:PasswordAuthenticationEvaluatorImpl.java   
@Override
protected void validateCredentialNotNull(ConnectionEnvironment connEnv,PasswordType credential) {

    ProtectedStringType protectedString = credential.getValue();

    if (protectedString == null) {
        recordAuthenticationFailure(principal,"no stored password value");
        throw new AuthenticationCredentialsNotFoundException("web.security.provider.password.bad");
    }

}
项目:engerek    文件:AuthenticationEvaluatorImpl.java   
private boolean checkCredentials(MidPointPrincipal principal,T authnCtx,ConnectionEnvironment connEnv) {

    UserType userType = principal.getUser();
    CredentialsType credentials = userType.getCredentials();
    if (credentials == null || getCredential(credentials) == null) {
        recordAuthenticationFailure(principal,"no credentials in user");
        throw new AuthenticationCredentialsNotFoundException("web.security.provider.invalid");
    }

    CredentialPolicyType credentialsPolicy = getCredentialsPolicy(principal,authnCtx);

    // Lockout
    if (isLockedOut(getCredential(credentials),credentialsPolicy)) {
        recordAuthenticationFailure(principal,"password locked-out");
        throw new LockedException("web.security.provider.locked");
    }

    if (suportsAuthzCheck()) {
        // Authorizations
        if (!hasAnyAuthorization(principal)) {
            recordAuthenticationFailure(principal,"no authorizations");
            throw new disabledException("web.security.provider.access.denied");
        }
    }

    // Password age
    checkPasswordValidityAndAge(connEnv,credentialsPolicy);

    return passwordMatches(connEnv,authnCtx);
}
项目:engerek    文件:AuthenticationEvaluatorImpl.java   
/**
 * Special-purpose method used for Web Service authentication based on javax.security callbacks.
 * 
 * In that case there is no reasonable way how to reuse existing methods. Therefore this method is NOT part of the
 * AuthenticationEvaluator interface. It is mostly a glue to make the old Java security code work.
 */
public String getAndCheckUserPassword(ConnectionEnvironment connEnv,String enteredUsername) 
        throws AuthenticationCredentialsNotFoundException,UsernameNotFoundException {     

    MidPointPrincipal principal = getAndCheckPrincipal(connEnv,enteredUsername,true);

    UserType userType = principal.getUser();
    CredentialsType credentials = userType.getCredentials();
    if (credentials == null) {
        recordAuthenticationFailure(principal,"no credentials in user");
        throw new AuthenticationCredentialsNotFoundException("web.security.provider.invalid");
    }
    PasswordType passwordType = credentials.getpassword();
    SecurityPolicyType securityPolicy = principal.getApplicableSecurityPolicy();
    PasswordCredentialsPolicyType passwordCredentialsPolicy = SecurityUtil.getEffectivePasswordCredentialsPolicy(securityPolicy);

    // Lockout
    if (isLockedOut(passwordType,passwordCredentialsPolicy)) {
        recordAuthenticationFailure(principal,"password locked-out");
        throw new LockedException("web.security.provider.locked");
    }

    // Authorizations
    if (!hasAnyAuthorization(principal)) {
        recordAuthenticationFailure(principal,"no authorizations");
        throw new AccessDeniedException("web.security.provider.access.denied");
    }

    // Password age
    checkPasswordValidityAndAge(connEnv,passwordType.getValue(),passwordType.getMetadata(),passwordCredentialsPolicy);

    return getpassword(connEnv,passwordType.getValue());
}
项目:Open-Clinica-Data-Uploader    文件:GetStudyMetadataResponseHandler.java   
public static Document getodm(SOAPMessage response) throws XPathExpressionException,SAXException,ParserConfigurationException,SOAPException,TransformerException {
    Document document = todocument(response);
    String result = isAuthFailure(document);
    if (!StringUtils.isEmpty(result)) {
        throw new AuthenticationCredentialsNotFoundException("Problem calling OpenClinica web-services: " + result);
    }
    Node odmCDatanode = (Node) xpath.evaluate(odmSelector,XPathConstants.NODE);
    if (odmCDatanode == null) {
        return null;
    }
    String textContent = odmCDatanode.getTextContent(); //Todo: Add handling case when no ODM is served by OC
    Document odm = SoapUtils.unescapeCdataxML(textContent);
    return odm;
}
项目:Open-Clinica-Data-Uploader    文件:OCResponseHandler.java   
public static String parseGenericResponse(SOAPMessage response,String selector) throws Exception {
    Document document = todocument(response);
    System.out.println("-->" + SoapUtils.soapMessagetoString(response));
    if (! isAuthFailure(document).equals("")) {
        throw new AuthenticationCredentialsNotFoundException("Authentication against OpenClinica unsuccessfull");
    }
    XPath xpath = XPathFactory.newInstance().newXPath();
    Node importDataResponseNode = (Node) xpath.evaluate(selector,XPathConstants.NODE);
        return errorNode.getTextContent();
    }
    return null;
}
项目:communote-server    文件:SwitchUserHelper.java   
/**
 * Create an authentication for the target user that will contain the current auth as granted
 * authentication. This method does not do any checking if the current user is actually alowed
 * to do the switching (therefore it is a private method).
 *
 * @param targetUser
 *            the user for the new authentication
 * @return the authentication of the target user
 */
private static Authentication createSwitchUserAuthentication(User targetUser) {

    UsernamePasswordAuthenticationToken targetUserAuthentication;

    Authentication currentAuth;

    try {
        // Check first if we are already switched.
        currentAuth = removeSwitchedUser();
    } catch (AuthenticationCredentialsNotFoundException e) {
        currentAuth = SecurityContextHolder.getContext().getAuthentication();
    }

    org.springframework.security.core.userdetails.User targetUserDetails = new UserDetails(
            targetUser,targetUser.getAlias());

    GrantedAuthority switchAuthority = new SwitchUserGrantedAuthority(ROLE_SWITCH_ORGINAL_USER,currentAuth);

    // add the new switch user authority
    List<GrantedAuthority> newAuths = new ArrayList<GrantedAuthority>();
    for (GrantedAuthority authority : targetUserDetails.getAuthorities()) {
        // only use roles that are allowed
        if (ALLOWED_SWITCH_ROLE_NAMES.contains(authority.getAuthority())) {
            newAuths.add(authority);
        }
    }
    newAuths.add(switchAuthority);

    // create the new authentication token
    targetUserAuthentication = new UsernamePasswordAuthenticationToken(targetUserDetails,targetUser.getpassword(),newAuths);

    return targetUserAuthentication;
}

今天关于Java Future-Spring Authentication在AuditorAware中为空java auth fail的讲解已经结束,谢谢您的阅读,如果想了解更多关于asp.net-core – options的用途.AutomaticAuthenticate with UseJwtBearerAuthentication、org.springframework.security.authentication.AbstractAuthenticationToken的实例源码、org.springframework.security.authentication.AnonymousAuthenticationToken的实例源码、org.springframework.security.authentication.AuthenticationCredentialsNotFoundException的实例源码的相关知识,请在本站搜索。

本文标签: