Search in sources :

Example 41 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project Spring-5.0-By-Example by PacktPublishing.

the class AuthenticationService method authenticate.

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String nickname = authentication.getName();
    String password = (String) authentication.getCredentials();
    CredentialData credentialData = this.credentialUserDetailsService.loadUserByUsername(nickname);
    if (Objects.isNull(credentialData) || !credentialData.getEmail().equalsIgnoreCase(nickname)) {
        throw new BadCredentialsException("email not found or invalid.");
    }
    if (!password.equals(credentialData.getPassword())) {
        throw new BadCredentialsException("wrong password.");
    }
    return new UsernamePasswordAuthenticationToken(credentialData, password, credentialData.getAuthorities());
}
Also used : CredentialData(springfive.airline.authservice.domain.data.CredentialData) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException)

Example 42 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project fw-cloud-framework by liuweijw.

the class AjaxLoginSuccessHandler method extractAndDecodeHeader.

private String[] extractAndDecodeHeader(String header) throws IOException {
    byte[] base64Token = header.substring(6).getBytes("UTF-8");
    byte[] decoded;
    try {
        decoded = Base64.decode(base64Token);
    } catch (IllegalArgumentException e) {
        throw new BadCredentialsException("Failed to decode basic authentication token");
    }
    String token = new String(decoded, CommonConstant.UTF8);
    int delim = token.indexOf(":");
    if (delim == -1) {
        throw new BadCredentialsException("Invalid basic authentication token");
    }
    return new String[] { token.substring(0, delim), token.substring(delim + 1) };
}
Also used : BadCredentialsException(org.springframework.security.authentication.BadCredentialsException)

Example 43 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project fw-cloud-framework by liuweijw.

the class AjaxLoginSuccessHandler method onAuthenticationSuccess.

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
    String header = request.getHeader(SecurityConstant.AUTHORIZATION);
    if (StringHelper.isBlank(header) || !header.startsWith(SecurityConstant.BASIC)) {
        throw new UnapprovedClientAuthenticationException("请求头中client信息为空");
    }
    try {
        String[] tokens = extractAndDecodeHeader(header);
        assert tokens.length == 2;
        String clientId = tokens[0];
        String clientSecret = tokens[1];
        JSONObject params = new JSONObject();
        params.put("clientId", clientId);
        params.put("clientSecret", clientSecret);
        params.put("authentication", authentication);
        ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId);
        TokenRequest tokenRequest = new TokenRequest(MapUtil.newHashMap(), clientId, clientDetails.getScope(), "mobile");
        OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(clientDetails);
        OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request, authentication);
        OAuth2AccessToken oAuth2AccessToken = authorizationServerTokenServices.createAccessToken(oAuth2Authentication);
        response.setCharacterEncoding(CommonConstant.UTF8);
        response.setContentType(CommonConstant.CONTENT_TYPE);
        PrintWriter printWriter = response.getWriter();
        printWriter.append(objectMapper.writeValueAsString(oAuth2AccessToken));
    } catch (IOException e) {
        throw new BadCredentialsException("Failed to decode basic authentication token");
    }
}
Also used : OAuth2Request(org.springframework.security.oauth2.provider.OAuth2Request) ClientDetails(org.springframework.security.oauth2.provider.ClientDetails) JSONObject(com.alibaba.fastjson.JSONObject) UnapprovedClientAuthenticationException(org.springframework.security.oauth2.common.exceptions.UnapprovedClientAuthenticationException) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) TokenRequest(org.springframework.security.oauth2.provider.TokenRequest) IOException(java.io.IOException) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) PrintWriter(java.io.PrintWriter)

Example 44 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project tutorials by eugenp.

the class CustomDaoAuthenticationProvider method authenticate.

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String name = authentication.getName();
    String password = authentication.getCredentials().toString();
    UserDetails u = null;
    try {
        u = getUserDetailsService().loadUserByUsername(name);
    } catch (UsernameNotFoundException ex) {
        log.error("User '" + name + "' not found");
    } catch (Exception e) {
        log.error("Exception in CustomDaoAuthenticationProvider: " + e);
    }
    if (u != null) {
        if (u.getPassword().equals(password)) {
            return new UsernamePasswordAuthenticationToken(u, password, u.getAuthorities());
        }
    }
    throw new BadCredentialsException(messages.getMessage("CustomDaoAuthenticationProvider.badCredentials", "Bad credentials"));
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) UserDetails(org.springframework.security.core.userdetails.UserDetails) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) AuthenticationException(org.springframework.security.core.AuthenticationException)

Example 45 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project tutorials by eugenp.

the class CustomAuthenticationProvider method authenticate.

@Override
public Authentication authenticate(Authentication auth) throws AuthenticationException {
    final User user = userRepository.findByEmail(auth.getName());
    if ((user == null)) {
        throw new BadCredentialsException("Invalid username or password");
    }
    final Authentication result = super.authenticate(auth);
    return new UsernamePasswordAuthenticationToken(user, result.getCredentials(), result.getAuthorities());
}
Also used : User(org.baeldung.rolesauthorities.model.User) Authentication(org.springframework.security.core.Authentication) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException)

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