Search in sources :

Example 36 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project ArachneCentralAPI by OHDSI.

the class AuthenticationSystemTokenFilter method doFilter.

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    String token = request.getHeader(tokenHeader);
    if (token != null) {
        DataNode dataNode = baseDataNodeService.findByToken(token).orElseThrow(() -> new BadCredentialsException("dataNode not found"));
        if (SecurityContextHolder.getContext().getAuthentication() == null) {
            GrantedAuthority dataNodeAuthority = new SimpleGrantedAuthority("ROLE_" + Roles.ROLE_DATA_NODE);
            Collection<GrantedAuthority> authorityCollection = new ArrayList<>();
            authorityCollection.add(dataNodeAuthority);
            DataNodeAuthenticationToken authentication = new DataNodeAuthenticationToken(token, dataNode, authorityCollection);
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
    }
    filterChain.doFilter(servletRequest, servletResponse);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) DataNode(com.odysseusinc.arachne.portal.model.DataNode) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) ArrayList(java.util.ArrayList) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException)

Example 37 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project ArachneCentralAPI by OHDSI.

the class AuthenticationTokenFilter method doFilter.

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException, AuthenticationException {
    try {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String authToken = httpRequest.getHeader(tokenHeader);
        if (authToken == null && httpRequest.getCookies() != null) {
            for (Cookie cookie : httpRequest.getCookies()) {
                if (cookie.getName().equalsIgnoreCase(tokenHeader)) {
                    authToken = cookie.getValue();
                }
            }
        }
        if (authToken != null) {
            String username = this.tokenUtils.getUsernameFromToken(authToken);
            if (tokenUtils.isExpired(authToken)) {
                if (((HttpServletRequest) request).getRequestURI().startsWith("/api")) {
                    if (username != null) {
                        throw new BadCredentialsException("token expired");
                    }
                }
            }
            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
                if (this.tokenUtils.validateToken(authToken, userDetails)) {
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpRequest));
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                    TenantContext.setCurrentTenant(((ArachneUser) userDetails).getActiveTenantId());
                }
            }
        }
        chain.doFilter(request, response);
    } catch (AuthenticationException ex) {
        logger.debug(ex.getMessage(), ex);
        ((HttpServletResponse) response).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        JsonResult<Boolean> result = new JsonResult<>(JsonResult.ErrorCode.UNAUTHORIZED);
        result.setResult(Boolean.FALSE);
        response.getOutputStream().write(objectMapper.writeValueAsString(result).getBytes());
        response.setContentType("application/json");
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) Cookie(javax.servlet.http.Cookie) UserDetails(org.springframework.security.core.userdetails.UserDetails) AuthenticationException(org.springframework.security.core.AuthenticationException) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) WebAuthenticationDetailsSource(org.springframework.security.web.authentication.WebAuthenticationDetailsSource) JsonResult(com.odysseusinc.arachne.commons.api.v1.dto.util.JsonResult)

Example 38 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project kylo by Teradata.

the class ActiveDirectoryAuthenticationProvider method authenticate.

/* (non-Javadoc)
     * @see org.springframework.security.ldap.authentication.AbstractLdapAuthenticationProvider#authenticate(org.springframework.security.core.Authentication)
     */
@Override
public Authentication authenticate(Authentication authentication) throws org.springframework.security.core.AuthenticationException {
    Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication, this.messages.getMessage("LdapAuthenticationProvider.onlySupports", "Only UsernamePasswordAuthenticationToken is supported"));
    final UsernamePasswordAuthenticationToken userToken = (UsernamePasswordAuthenticationToken) authentication;
    final UsernamePasswordAuthenticationToken authToken = this.serviceToken != null ? this.serviceToken : userToken;
    if (this.logger.isDebugEnabled()) {
        this.logger.debug("Processing authentication request for user: " + userToken.getName());
    }
    if (!StringUtils.hasLength(userToken.getName())) {
        throw new BadCredentialsException(this.messages.getMessage("LdapAuthenticationProvider.emptyUsername", "Empty Username"));
    }
    String credentials = String.valueOf((char[]) authToken.getCredentials());
    if (!StringUtils.hasLength(credentials)) {
        throw new BadCredentialsException(this.messages.getMessage("AbstractLdapAuthenticationProvider.emptyPassword", "Empty Password"));
    }
    DirContextOperations userData = doAuthentication(userToken);
    Collection<? extends GrantedAuthority> authorities = loadUserAuthorities(userData, authToken.getName(), credentials);
    UserDetails user = this.userDetailsContextMapper.mapUserFromContext(userData, userToken.getName(), authorities);
    return createSuccessfulAuthentication(userToken, user);
}
Also used : UserDetails(org.springframework.security.core.userdetails.UserDetails) DirContextOperations(org.springframework.ldap.core.DirContextOperations) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException)

Example 39 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project spring-security-oauth by spring-projects.

the class OAuth2AuthenticationEntryPointTests method testCommenceWithOAuth2Exception.

@Test
public void testCommenceWithOAuth2Exception() throws Exception {
    request.addHeader("Accept", MediaType.APPLICATION_JSON_VALUE);
    entryPoint.commence(request, response, new BadCredentialsException("Bad", new InvalidClientException("Bad client")));
    assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatus());
    assertEquals("{\"error\":\"invalid_client\",\"error_description\":\"Bad client\"}", response.getContentAsString());
    assertTrue(response.getContentType().contains(MediaType.APPLICATION_JSON_VALUE));
    assertEquals(null, response.getErrorMessage());
}
Also used : InvalidClientException(org.springframework.security.oauth2.common.exceptions.InvalidClientException) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) Test(org.junit.Test)

Example 40 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project spring-security-oauth by spring-projects.

the class ResourceOwnerPasswordTokenGranter method getOAuth2Authentication.

@Override
protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
    Map<String, String> parameters = new LinkedHashMap<String, String>(tokenRequest.getRequestParameters());
    String username = parameters.get("username");
    String password = parameters.get("password");
    // Protect from downstream leaks of password
    parameters.remove("password");
    Authentication userAuth = new UsernamePasswordAuthenticationToken(username, password);
    ((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);
}
Also used : AccountStatusException(org.springframework.security.authentication.AccountStatusException) AbstractAuthenticationToken(org.springframework.security.authentication.AbstractAuthenticationToken) OAuth2Request(org.springframework.security.oauth2.provider.OAuth2Request) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) InvalidGrantException(org.springframework.security.oauth2.common.exceptions.InvalidGrantException) LinkedHashMap(java.util.LinkedHashMap)

Aggregations

BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)170 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)63 Authentication (org.springframework.security.core.Authentication)57 Test (org.junit.jupiter.api.Test)29 Test (org.junit.Test)27 AuthenticationException (org.springframework.security.core.AuthenticationException)23 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)20 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)20 UserDetails (org.springframework.security.core.userdetails.UserDetails)20 GrantedAuthority (org.springframework.security.core.GrantedAuthority)15 AuthenticationManager (org.springframework.security.authentication.AuthenticationManager)14 UsernameNotFoundException (org.springframework.security.core.userdetails.UsernameNotFoundException)13 AuthenticationServiceException (org.springframework.security.authentication.AuthenticationServiceException)12 HttpServletRequest (javax.servlet.http.HttpServletRequest)11 FilterChain (jakarta.servlet.FilterChain)10 IOException (java.io.IOException)10 ArrayList (java.util.ArrayList)10 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)10 TestingAuthenticationToken (org.springframework.security.authentication.TestingAuthenticationToken)9 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)7