Java tutorial
/* * Copyright 2014. Vadim Baranov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.vader.common.cxf; import org.apache.commons.lang3.StringUtils; import org.apache.ws.security.WSSecurityException; import org.apache.ws.security.handler.RequestData; import org.apache.ws.security.message.token.UsernameToken; import org.apache.ws.security.validate.UsernameTokenValidator; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.context.SecurityContextHolder; /** * @author Vadim Baranov */ public class SpringSecurityUsernameTokenValidator extends UsernameTokenValidator { private AuthenticationManager authenticationManager; public void setAuthenticationManager(AuthenticationManager authenticationManager) { this.authenticationManager = authenticationManager; } @Override protected void verifyPlaintextPassword(UsernameToken usernameToken, RequestData data) throws WSSecurityException { SecurityContextHolder.clearContext(); final String login = usernameToken.getName(); final String password = usernameToken.getPassword(); if (StringUtils.isBlank(login) || StringUtils.isBlank(password)) { throw new WSSecurityException( String.format("Auth failed for login=[%s], password=[%s]", login, password)); } try { final Authentication authentication = authenticationManager .authenticate(new UsernamePasswordAuthenticationToken(login, password)); SecurityContextHolder.getContext().setAuthentication(authentication); } catch (AuthenticationException e) { throw new WSSecurityException( String.format("Auth failed for login=[%s], password=[%s]", login, password), e); } } }