Skip to content

Instantly share code, notes, and snippets.

@jogaco
Last active August 28, 2017 10:44
Show Gist options
  • Save jogaco/5950347 to your computer and use it in GitHub Desktop.
Save jogaco/5950347 to your computer and use it in GitHub Desktop.
Java REST Web Service securization for Apache CXF 2.3.3 with Spring Security 3.0.5: Basic Authentication
import javax.ws.rs.core.Response;
import org.apache.cxf.configuration.security.AuthorizationPolicy;
import org.apache.cxf.interceptor.security.AccessDeniedException;
import org.apache.cxf.jaxrs.ext.RequestHandler;
import org.apache.cxf.jaxrs.model.ClassResourceInfo;
import org.apache.cxf.message.Message;
import org.apache.log4j.Logger;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
public class BasicAuthAuthorizationInterceptor implements RequestHandler {
protected Logger log = Logger.getLogger(getClass());
private UserDetailsService userDetailsService;
private PasswordEncoder passwordEncoder;
public void setUserDetailsService(UserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}
public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
this.passwordEncoder = passwordEncoder;
}
public Response handleRequest(Message m, ClassResourceInfo resourceClass) {
AuthorizationPolicy policy = (AuthorizationPolicy)m.get(AuthorizationPolicy.class);
if (policy != null) {
String username = policy.getUserName();
String password = policy.getPassword();
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
boolean passwordValid = passwordEncoder.isPasswordValid(userDetails.getPassword(), password, null);
if (passwordValid) {
Authentication prevAuth = SecurityContextHolder.getContext().getAuthentication();
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(userDetails, userDetails.getPassword(), userDetails.getAuthorities());
if (!auth.equals(prevAuth)) {
SecurityContextHolder.getContext().setAuthentication(auth);
}
// let request to continue
return null;
}
}
throw new AccessDeniedException("basic auth required");
}
}
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxws="http://cxf.apache.org/jaxws"
xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xmlns:cxf="http://cxf.apache.org/core"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd
http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd">
<import resource="classpath:META-INF/cxf/cxf.xml"/>
<import resource="classpath:META-INF/cxf/cxf-extension-soap.xml"/>
<import resource="classpath:META-INF/cxf/cxf-extension-jaxrs-binding.xml"/>
<import resource="classpath:META-INF/cxf/cxf-servlet.xml"/>
<bean id="jsonProvider" class="org.codehaus.jackson.jaxrs.JacksonJsonProvider"/>
<bean id="mySecurityInterceptor" class="es.jogaco.security.BasicAuthAuthorizationInterceptor">
<property name="userDetailsService" ref="userDao"/>
<property name="passwordEncoder" ref="passwordEncoder"/>
</bean>
<!-- SOAP web services -->
<!--
<jaxws:endpoint id="userService" implementor="#userManager" address="/UserService"/>
-->
<!-- Add new endpoints for additional services you'd like to expose -->
<jaxrs:server address="/api">
<jaxrs:features>
<cxf:logging/>
</jaxrs:features>
<jaxrs:serviceBeans>
<ref bean="userManager"/>
</jaxrs:serviceBeans>
<jaxrs:providers>
<ref bean="jsonProvider"/>
<ref bean="mySecurityInterceptor"/>
<bean id="securityExceptionMapper" class="es.jogaco.providers.SecurityExceptionMapper"/>
</jaxrs:providers>
<jaxrs:extensionMappings>
<entry key="json" value="application/json"/>
<entry key="xml" value="application/xml"/>
<entry key="feed" value="application/atom+xml"/>
</jaxrs:extensionMappings>
</jaxrs:server>
</beans>
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd">
<http auto-config="true" lowercase-comparisons="false">
<intercept-url pattern="/services/**" filters="none"/>
<intercept-url pattern="/images/**" filters="none"/>
<intercept-url pattern="/styles/**" filters="none"/>
<intercept-url pattern="/scripts/**" filters="none"/>
<intercept-url pattern="/admin/**" access="ROLE_ADMIN"/>
<intercept-url pattern="/passwordHint*" access="ROLE_ANONYMOUS,ROLE_ADMIN,ROLE_USER"/>
<!-- <intercept-url pattern="/signup*" access="ROLE_ANONYMOUS,ROLE_ADMIN,ROLE_USER"/> -->
<intercept-url pattern="/**/*.action*" access="ROLE_ADMIN,ROLE_USER"/>
<form-login login-page="/login" authentication-failure-url="/login?error=true" login-processing-url="/j_security_check"/>
<remember-me user-service-ref="userDao" key="e37f4b31-0c45-11dd-bd0b-0800200c9a66"/>
</http>
<authentication-manager>
<authentication-provider user-service-ref="userDao">
<password-encoder ref="passwordEncoder"/>
</authentication-provider>
</authentication-manager>
<!-- Override the default password-encoder (SHA) by uncommenting the following and changing the class -->
<!-- <bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.ShaPasswordEncoder"/> -->
<global-method-security secured-annotations="enabled">
<protect-pointcut expression="execution(* *..service.UserManager.getUsers(..))" access="ROLE_ADMIN"/>
<protect-pointcut expression="execution(* *..service.UserManager.removeUser(..))" access="ROLE_ADMIN"/>
</global-method-security>
</beans:beans>
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import org.apache.cxf.interceptor.security.AccessDeniedException;
public class SecurityExceptionMapper implements
ExceptionMapper<AccessDeniedException> {
public Response toResponse(AccessDeniedException exception) {
return Response.status(Response.Status.UNAUTHORIZED).header("WWW-Authenticate", "Basic").build();
}
}
@kienvl1b
Copy link

kienvl1b commented May 10, 2016

can you please share us full source code, sir?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment