Spring Security Authentication using RestTemplate - java

I have 2 spring web apps that provide 2 separate set of services. Web App 1 has Spring Security implemented using a user-based authentication.
Now, Web App 2 needs to access the service of Web App 1. Normally, we would use the RestTemplate class to make requests to other web services.
How do we pass the authentication credentials in the request of Web App 2 to Web App 1

Here is a solution that works very well with Spring 3.1 and Apache HttpComponents 4.1 I created based various answers on this site and reading the spring RestTempalte source code. I am sharing in hopes of saving others time, I think spring should just have some code like this built in but it does not.
RestClient client = new RestClient();
client.setApplicationPath("someApp");
String url = client.login("theuser", "123456");
UserPortfolio portfolio = client.template().getForObject(client.apiUrl("portfolio"),
UserPortfolio.class);
Below is the Factory class which setups up the HttpComponents context to be the same on every request with the RestTemplate.
public class StatefullHttpComponentsClientHttpRequestFactory extends
HttpComponentsClientHttpRequestFactory
{
private final HttpContext httpContext;
public StatefullHttpComponentsClientHttpRequestFactory(HttpClient httpClient, HttpContext httpContext)
{
super(httpClient);
this.httpContext = httpContext;
}
#Override
protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri)
{
return this.httpContext;
}
}
Below is Statefull Rest template that you can use to remember cookies, once you log in with it will remember the JSESSIONID and sent it on subsequent requests.
public class StatefullRestTemplate extends RestTemplate
{
private final HttpClient httpClient;
private final CookieStore cookieStore;
private final HttpContext httpContext;
private final StatefullHttpComponentsClientHttpRequestFactory statefullHttpComponentsClientHttpRequestFactory;
public StatefullRestTemplate()
{
super();
httpClient = new DefaultHttpClient();
cookieStore = new BasicCookieStore();
httpContext = new BasicHttpContext();
httpContext.setAttribute(ClientContext.COOKIE_STORE, getCookieStore());
statefullHttpComponentsClientHttpRequestFactory = new StatefullHttpComponentsClientHttpRequestFactory(httpClient, httpContext);
super.setRequestFactory(statefullHttpComponentsClientHttpRequestFactory);
}
public HttpClient getHttpClient()
{
return httpClient;
}
public CookieStore getCookieStore()
{
return cookieStore;
}
public HttpContext getHttpContext()
{
return httpContext;
}
public StatefullHttpComponentsClientHttpRequestFactory getStatefulHttpClientRequestFactory()
{
return statefullHttpComponentsClientHttpRequestFactory;
}
}
Here is a class to represent a rest client so that you can call into an app secured with spring
security.
public class RestClient
{
private String host = "localhost";
private String port = "8080";
private String applicationPath;
private String apiPath = "api";
private String loginPath = "j_spring_security_check";
private String logoutPath = "logout";
private final String usernameInputFieldName = "j_username";
private final String passwordInputFieldName = "j_password";
private final StatefullRestTemplate template = new StatefullRestTemplate();
/**
* This method logs into a service by doing an standard http using the configuration in this class.
*
* #param username
* the username to log into the application with
* #param password
* the password to log into the application with
*
* #return the url that the login redirects to
*/
public String login(String username, String password)
{
MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
form.add(usernameInputFieldName, username);
form.add(passwordInputFieldName, password);
URI location = this.template.postForLocation(loginUrl(), form);
return location.toString();
}
/**
* Logout by doing an http get on the logout url
*
* #return result of the get as ResponseEntity
*/
public ResponseEntity<String> logout()
{
return this.template.getForEntity(logoutUrl(), String.class);
}
public String applicationUrl(String relativePath)
{
return applicationUrl() + "/" + checkNotNull(relativePath);
}
public String apiUrl(String relativePath)
{
return applicationUrl(apiPath + "/" + checkNotNull(relativePath));
}
public StatefullRestTemplate template()
{
return template;
}
public String serverUrl()
{
return "http://" + host + ":" + port;
}
public String applicationUrl()
{
return serverUrl() + "/" + nullToEmpty(applicationPath);
}
public String loginUrl()
{
return applicationUrl(loginPath);
}
public String logoutUrl()
{
return applicationUrl(logoutPath);
}
public String apiUrl()
{
return applicationUrl(apiPath);
}
public void setLogoutPath(String logoutPath)
{
this.logoutPath = logoutPath;
}
public String getHost()
{
return host;
}
public void setHost(String host)
{
this.host = host;
}
public String getPort()
{
return port;
}
public void setPort(String port)
{
this.port = port;
}
public String getApplicationPath()
{
return applicationPath;
}
public void setApplicationPath(String contextPath)
{
this.applicationPath = contextPath;
}
public String getApiPath()
{
return apiPath;
}
public void setApiPath(String apiPath)
{
this.apiPath = apiPath;
}
public String getLoginPath()
{
return loginPath;
}
public void setLoginPath(String loginPath)
{
this.loginPath = loginPath;
}
public String getLogoutPath()
{
return logoutPath;
}
#Override
public String toString()
{
StringBuilder builder = new StringBuilder();
builder.append("RestClient [\n serverUrl()=");
builder.append(serverUrl());
builder.append(", \n applicationUrl()=");
builder.append(applicationUrl());
builder.append(", \n loginUrl()=");
builder.append(loginUrl());
builder.append(", \n logoutUrl()=");
builder.append(logoutUrl());
builder.append(", \n apiUrl()=");
builder.append(apiUrl());
builder.append("\n]");
return builder.toString();
}
}

I was in the same situation. Here there is my solution.
Server - spring security config
<sec:http>
<sec:intercept-url pattern="/**" access="ROLE_USER" method="POST"/>
<sec:intercept-url pattern="/**" filters="none" method="GET"/>
<sec:http-basic />
</sec:http>
<sec:authentication-manager alias="authenticationManager">
<sec:authentication-provider>
<sec:user-service>
<sec:user name="${rest.username}" password="${rest.password}" authorities="ROLE_USER"/>
</sec:user-service>
</sec:authentication-provider>
</sec:authentication-manager>
Client side RestTemplate config
<bean id="httpClient" class="org.apache.commons.httpclient.HttpClient">
<constructor-arg ref="httpClientParams"/>
<property name="state" ref="httpState"/>
</bean>
<bean id="httpState" class="CustomHttpState">
<property name="credentials" ref="credentials"/>
</bean>
<bean id="credentials" class="org.apache.commons.httpclient.UsernamePasswordCredentials">
<constructor-arg value="${rest.username}"/>
<constructor-arg value="${rest.password}"/>
</bean>
<bean id="httpClientFactory" class="org.springframework.http.client.CommonsClientHttpRequestFactory">
<constructor-arg ref="httpClient"/>
</bean>
<bean class="org.springframework.web.client.RestTemplate">
<constructor-arg ref="httpClientFactory"/>
</bean>
Custom HttpState implementation
/**
* Custom implementation of {#link HttpState} with credentials property.
*
* #author banterCZ
*/
public class CustomHttpState extends HttpState {
/**
* Set credentials property.
*
* #param credentials
* #see #setCredentials(org.apache.commons.httpclient.auth.AuthScope, org.apache.commons.httpclient.Credentials)
*/
public void setCredentials(final Credentials credentials) {
super.setCredentials(AuthScope.ANY, credentials);
}
}
Maven dependency
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>

The RestTemplate is very basic and limited; there doesn't seem to be an easy way to do this. The best way is probably to implement digest of basic auth in Web App 1. Then use Apache HttpClient directly to access the rest services from Web App 2.
That being said, for testing I was able to work around this with a big hack. Basically you use the RestTemplate to submit the login (j_spring_security_check), parse out the jsessionid from the request headers, then submit the rest request. Here's the code, but I doubt it's the best solution for production ready code.
public final class RESTTest {
public static void main(String[] args) {
RestTemplate rest = new RestTemplate();
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
#Override
public boolean verify(String s, SSLSession sslsession) {
return true;
}
});
// setting up a trust store with JCA is a whole other issue
// this assumes you can only log in via SSL
// you could turn that off, but not on a production site!
System.setProperty("javax.net.ssl.trustStore", "/path/to/cacerts");
System.setProperty("javax.net.ssl.trustStorePassword", "somepassword");
String jsessionid = rest.execute("https://localhost:8443/j_spring_security_check", HttpMethod.POST,
new RequestCallback() {
#Override
public void doWithRequest(ClientHttpRequest request) throws IOException {
request.getBody().write("j_username=user&j_password=user".getBytes());
}
}, new ResponseExtractor<String>() {
#Override
public String extractData(ClientHttpResponse response) throws IOException {
List<String> cookies = response.getHeaders().get("Cookie");
// assuming only one cookie with jsessionid as the only value
if (cookies == null) {
cookies = response.getHeaders().get("Set-Cookie");
}
String cookie = cookies.get(cookies.size() - 1);
int start = cookie.indexOf('=');
int end = cookie.indexOf(';');
return cookie.substring(start + 1, end);
}
});
rest.put("http://localhost:8080/rest/program.json;jsessionid=" + jsessionid, new DAO("REST Test").asJSON());
}
}
Note for this to work, you need to create a trust store in JCA so the SSL connection can actually be made. I assume you don't want to have Spring Security's login be over plain HTTP for a production site since that would be a massive security hole.

There's a simple way to do this in case you are someone who's looking for a simple call and not a API consumer.
HttpClient client = new HttpClient();
client.getParams().setAuthenticationPreemptive(true);
Credentials defaultcreds = new UsernamePasswordCredentials("username", "password");
RestTemplate restTemplate = new RestTemplate();
restTemplate.setRequestFactory(new CommonsClientHttpRequestFactory(client));
client.getState().setCredentials(AuthScope.ANY, defaultcreds);

The following will authenticate and return the session cookie:
String sessionCookie= restTemplate.execute(uri, HttpMethod.POST, request -> {
request.getBody().write(("j_username=USER_NAME&j_password=PASSWORD").getBytes());
}, response -> {
AbstractClientHttpResponse r = (AbstractClientHttpResponse) response;
HttpHeaders headers = r.getHeaders();
return headers.get("Set-Cookie").get(0);
});

The currently authenticated user credentials should be available in Web App 1 on Authentication object, which is accessible through SecurityContext (for example, you can retrieve it by calling SecurityContextHolder.getContext().getAuthentication()).
After you retrieve the credentials, you can use them to access Web App 2.
You can pass "Authentiation" header with RestTemplate by either extending it with a decorator (as described here) or using RestTemplate.exchange() method, as described in this forum post.

This is very similar to ams's approach, except I've completely encapsulated the concern of maintaining the session cookie in the StatefulClientHttpRequestFactory. Also by decorating an existing ClientHttpRequestFactory with this behaviour, it can be used with any underlying ClientHttpRequestFactory and isn't bound to a specific implementation.
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import static java.lang.String.format;
/**
* Decorates a ClientHttpRequestFactory to maintain sessions (cookies)
* to web servers.
*/
public class StatefulClientHttpRequestFactory implements ClientHttpRequestFactory {
protected final Log logger = LogFactory.getLog(this.getClass());
private final ClientHttpRequestFactory requestFactory;
private final Map<String, String> hostToCookie = new HashMap<>();
public StatefulClientHttpRequestFactory(ClientHttpRequestFactory requestFactory){
this.requestFactory = requestFactory;
}
#Override
public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException {
ClientHttpRequest request = requestFactory.createRequest(uri, httpMethod);
final String host = request.getURI().getHost();
String cookie = getCookie(host);
if(cookie != null){
logger.debug(format("Setting request Cookie header to [%s]", cookie));
request.getHeaders().set("Cookie", cookie);
}
//decorate the request with a callback to process 'Set-Cookie' when executed
return new CallbackClientHttpRequest(request, response -> {
List<String> responseCookie = response.getHeaders().get("Set-Cookie");
if(responseCookie != null){
setCookie(host, responseCookie.stream().collect(Collectors.joining("; ")));
}
return response;
});
}
private synchronized String getCookie(String host){
String cookie = hostToCookie.get(host);
return cookie;
}
private synchronized void setCookie(String host, String cookie){
hostToCookie.put(host, cookie);
}
private static class CallbackClientHttpRequest implements ClientHttpRequest{
private final ClientHttpRequest request;
private final Function<ClientHttpResponse, ClientHttpResponse> filter;
public CallbackClientHttpRequest(ClientHttpRequest request, Function<ClientHttpResponse, ClientHttpResponse> filter){
this.request = request;
this.filter = filter;
}
#Override
public ClientHttpResponse execute() throws IOException {
ClientHttpResponse response = request.execute();
return filter.apply(response);
}
#Override
public OutputStream getBody() throws IOException {
return request.getBody();
}
#Override
public HttpMethod getMethod() {
return request.getMethod();
}
#Override
public URI getURI() {
return request.getURI();
}
#Override
public HttpHeaders getHeaders() {
return request.getHeaders();
}
}
}

Related

Provide different ClientInterceptor per request using Spring Web Services

I've created a custom web service client by extending WebServiceGatewaySupport and also implement custom ClientInterceptor to log some request/response data.
I have to create new interceptor for every call because it has to store some data about the request.
The problem occurs when I make two or more calls to my client. The first request applies its own interceptor with its clientId. The second should do the same. But since both requests use the same WebServicetemplate in my client, the second request replaces the interceptor with its own, with its clientId there.
As a result, I should get the following output to the console:
Request: clientId-1
Request: clientId-2
Response: clientId-1
Response: clientId-2
But I got this:
Request: clientId-1
Request: clientId-2
Response: clientId-2
Response: clientId-2
Here is come code examples (just for understanding how it should work):
#Data
class Response {
private final String result;
public Response(String result) {
this.result = result;
}
}
#Data
class Request {
private final String firstName;
private final String lastName;
}
#Data
class Context {
private final String clientId;
}
#Data
class Client {
private final String clientId;
private final String firstName;
private final String lastName;
}
class CustomInterceptor extends ClientInterceptorAdapter {
private final String clientId;
public CustomInterceptor(String clientId) {
this.clientId = clientId;
}
#Override
public boolean handleRequest(MessageContext messageContext) throws WebServiceClientException {
System.out.println("Request: " + clientId);
return true;
}
#Override
public boolean handleResponse(MessageContext messageContext) throws WebServiceClientException {
System.out.println("Response: " + clientId);
return true;
}
#Override
public boolean handleFault(MessageContext messageContext) throws WebServiceClientException {
System.out.println("Error: " + clientId);
return true;
}
}
#Component
class CustomClient extends WebServiceGatewaySupport {
public Response sendRequest(Request request, Context context) {
CustomInterceptor[] interceptors = {new CustomInterceptor(context.getClientId())};
setInterceptors(interceptors);
return (Response) getWebServiceTemplate().marshalSendAndReceive(request);
}
}
#Service
#RequiredArgsConstructor
class CustomService {
private final CustomClient customClient;
public String call(Request request, Context context) {
Response response = customClient.sendRequest(request, context);
return response.getResult();
}
}
#RestController
#RequestMapping("/test")
#RequiredArgsConstructor
class CustomController {
private final CustomService service;
public CustomController(CustomService service) {
this.service = service;
}
#PostMapping
public String test(#RequestBody Client client) {
Request request = new Request(client.getFirstName(), client.getLastName());
Context context = new Context(client.getClientId());
return service.call(request, context);
}
}
Is it possible to implement custom interceptors with some state for each call? Preferably without any locks on WebServicetemplate to avoid performance degradation.
Okay. I've found the solution for my case.
I've created an implementation of WebServiceMessageCallback and using it I'm saving data of each request not in interceptor but in WebServiceMessage's mime header.
#Data
class CustomMessageCallback implements WebServiceMessageCallback {
private final String clientId;
#Override
public void doWithMessage(WebServiceMessage message) throws IOException, TransformerException {
MimeHeaders headers = ((SaajSoapMessage) message).getSaajMessage().getMimeHeaders();
headers.addHeader("X-Client-Id", clientId);
}
}
And pass this callback in my client implementation:
#Component
class CustomClient extends WebServiceGatewaySupport {
public Response sendRequest(Request request, Context context) {
CustomInterceptor[] interceptors = {new CustomInterceptor()};
setInterceptors(interceptors);
return (Response) getWebServiceTemplate()
.marshalSendAndReceive(request, new CustomMessageCallback(context.getClientId()));
}
}
So now I can get this data while processing request/response/error via interceptor.
#Override
public boolean handleRequest(MessageContext messageContext) throws WebServiceClientException {
String clientId = ((SaajSoapMessage) messageContext.getRequest())
.getSaajMessage()
.getMimeHeaders()
.getHeader("X-Client-Id")[0];
System.out.println("Request: " + clientId);
return true;
}

Feign client Retryer with a new request interceptor?

I am currently building a feign client manually and passing Interceptors to it for authorization. I would like to have a smarter Retryer for some Response code.
public class myErrorEncoder extends ErrorDecoder.Default {
#Override
public Exception decode(final String methodKey, final Response response) {
if (response.status() == 401) {
String token = refreshToken(); // I would like to refresh the token and Edit the client
return new RetryableException("Token Expired will retry it", null);
} else {
return super.decode(methodKey, response);
}
}
}
Interceptor
#Bean public CustomInterceptor getInterceptor(String token) {
return new CustomInterceptor(token);}
Feign builder
private <T> T feignBuild(final Class<T> clazz, final String uri, final String token) {
return Feign
.builder().client(new ApacheHttpClient())
.encoder(new GsonEncoder())
.decoder(new ResponseEntityDecoder(feignDecoder())
.retryer(new Retryer.Default(1,100,3))
.errorDecoder(new ErrorDecoder())
.requestInterceptor(getInterceptor(token))
.contract(new ClientContract())
.logger(new Slf4jLogger(clazz)).target(clazz, uri);
}
Now I would like to update feign client with the refreshed token and retry.
Is there a way get access to the client instance and configure it.
Your use of the interceptor is incorrect. Interceptors are re-applied during a retry, but they are instantiated only once and are expected to be thread safe. To achieve what you are looking for will need to separate the token generation from the interceptor and have the interceptor request a new token.
public class TokenInterceptor() {
TokenService tokenService;
public TokenInterceptor(TokenService tokenService) {
this.tokenService = tokenService;
}
public void apply(RequestTemplate template) {
/* getToken() should create a new token */
String token = this.tokenService.getToken();
template.header("Authorization", "Bearer " + token);
}
}
This will ensure that a new token is created each retry cycle.

Why is Authorization Header missing?

I have Eureka and connected services Zuul:8090, AuthService:[any_port].
I send ../login request to Zuul he send to AuthSercice. Then AuthSerice put into Header JWT Authentication.
#Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
String token = Jwts.builder()
.setSubject( ((User) authResult.getPrincipal()).getUsername())
.setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
.signWith(SignatureAlgorithm.HS512, SECRET)
.compact();
response.addHeader("Authorization", "Bearer "+ token); // this is missing
response.addHeader("Authorization2", "Bearer " + token); // ok
}
I do request on Postman. Request result
First I tried to use JWT in Monoliths. There wasn't any problem, and Authorization Token can be added.
Why is Authorization Header missing?
It is because of a built-in mechanism in Zuul -- it automatically filters out sensitive headers, such as Authorization and Cookies, to protect sensitive information from being forwarded to downstream services.
That is why you can not get the header with the name Authorization.
if you want your downstream services to receive them anyway, just define the filter by yourself in your Zuul config file, instead of using default.
zuul:
routes:
users:
path: your url pattern
sensitiveHeaders: //put nothing here!! leave it blank, the filter will be off
url: downstream url
Here is spring official explanation on sensitive headers: document
You need set the option for forwarding headers in Eureka.
For Login I would suggest to have a custom ZuulFilter.
public abstract class AuthenticationZuulFilter extends ZuulFilter {
private static final Log logger = getLog(AuthenticationZuulFilter.class);
private static final String BEARER_TOKEN_TYPE = "Bearer ";
private static final String PRE_ZUUL_FILTER_TYPE = "pre";
private AuthTokenProvider tokenProvider;
public AuthenticationZuulFilter(AuthTokenProvider tokenProvider) {
this.tokenProvider = tokenProvider;
}
#Override
public Object run() {
RequestContext ctx = getCurrentContext();
ctx.addZuulRequestHeader(X_USER_INFO_HEADER_NAME, buildUserInfoHeaderFromAuthentication());
ctx.addZuulRequestHeader(AUTHORIZATION, BEARER_TOKEN_TYPE + tokenProvider.getToken());
return null;
}
#Override
public String filterType() {
return PRE_ZUUL_FILTER_TYPE;
}
#Override
public int filterOrder() {
return 1;
}
This is an implementation of it can be like this.
#Component
public class UserAuthenticationZuulFilter extends AuthenticationZuulFilter {
#Value("#{'${user.allowed.paths}'.split(',')}")
private List<String> allowedPathAntPatterns;
private PathMatcher pathMatcher = new AntPathMatcher();
#Autowired
public UserAuthenticationZuulFilter (AuthTokenProvider tokenProvider) {
super(tokenProvider);
}
#Override
public boolean shouldFilter() {
Authentication auth = getContext().getAuthentication();
HttpServletRequest request = getCurrentContext().getRequest();
String requestUri = request.getRequestURI();
String requestMethod = request.getMethod();
return auth instanceof UserAuthenticationZuulFilter && GET.matches(requestMethod) && isAllowedPath(requestUri);
}
}

How to make Shiro return 403 Forbidden with Spring Boot rather than redirect to login.jsp

I have a server that is just an API endpoint, no client front-end, no jsp, no html. It uses Spring Boot and I'm trying to secure it with Shiro. The relevent parts of my SpringBootServletInitializer look like this. I'm trying to get Shiro to return a 403 response if it fails the roles lookup as defined in BasicRealm. Yet it seems to default to redirecting to a non-existent login.jsp and no matter what solution I seem to use. I can't override that. Any help would be greatly appreciated.
#SpringBootApplication
public class RestApplication extends SpringBootServletInitializer {
...
#Bean(name = "shiroFilter")
public ShiroFilterFactoryBean shiroFilter() {
ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
Map<String, String> filterChain = new HashMap<>();
filterChain.put("/admin/**", "roles[admin]");
shiroFilter.setFilterChainDefinitionMap(filterChain);
shiroFilter.setSecurityManager(securityManager());
return shiroFilter;
}
#Bean
public org.apache.shiro.mgt.SecurityManager securityManager() {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(userRealm());
CookieRememberMeManager rmm = new CookieRememberMeManager();
rmm.setCipherKey(Base64.decode("XXXXXXXXXXXXXXXXXXXXXX"));
securityManager.setRememberMeManager(rmm);
return securityManager;
}
#Bean(name = "userRealm")
#DependsOn("lifecycleBeanPostProcessor")
public BasicRealm userRealm() {
return new BasicRealm();
}
#Bean
public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
return new LifecycleBeanPostProcessor();
}
}
public class BasicRealm extends AuthorizingRealm {
private static Logger logger = UserService.logger;
private static final String REALM_NAME = "BASIC";
public BasicRealm() {
super();
}
#Override
protected AuthenticationInfo doGetAuthenticationInfo(final AuthenticationToken token)
throws AuthenticationException {
UsernamePasswordToken upToken = (UsernamePasswordToken) token;
String userid = upToken.getUsername();
User user = Global.INST.getUserService().getUserById(userid);
if (user == null) {
throw new UnknownAccountException("No account found for user [" + userid + "]");
}
return new SimpleAuthenticationInfo(userid, user.getHashedPass().toCharArray(), REALM_NAME);
}
#Override
protected AuthorizationInfo doGetAuthorizationInfo(final PrincipalCollection principals) {
String userid = (String) principals.getPrimaryPrincipal();
if (userid == null) {
return new SimpleAuthorizationInfo();
}
return new SimpleAuthorizationInfo(Global.INST.getUserService().getRoles(userid));
}
}
OK, here is how I solved it. I created a class ...
public class AuthFilter extends RolesAuthorizationFilter {
private static final String MESSAGE = "Access denied.";
#Override
protected boolean onAccessDenied(final ServletRequest request, final ServletResponse response) throws IOException {
HttpServletResponse httpResponse ;
try {
httpResponse = WebUtils.toHttp(response);
}
catch (ClassCastException ex) {
// Not a HTTP Servlet operation
return super.onAccessDenied(request, response) ;
}
if (MESSAGE == null) {
httpResponse.sendError(403);
} else {
httpResponse.sendError(403, MESSAGE);
}
return false; // No further processing.
}
}
... and then in my shiroFilter() method above I added this code ...
Map<String, Filter> filters = new HashMap<>();
filters.put("roles", new AuthFilter());
shiroFilter.setFilters(filters);
... hope this helps someone else.
In Shiro 1.4+ you can set the login url in your application.properties:
https://github.com/apache/shiro/blob/master/samples/spring-boot-web/src/main/resources/application.properties#L20
Earlier versions you should be able to set ShiroFilterFactoryBean.setLoginUrl("/login")
https://shiro.apache.org/static/current/apidocs/org/apache/shiro/spring/web/ShiroFilterFactoryBean.html

To send get request to Web API from Java Servlet

Common question
Is is possible to send get reguest from Java servlet's doGet method ? I need to check some "ticket" against my Web API .NET service, so can I call to this service from my custom servlet in the doGet method ?
public class IdentityProviderServlet extends HttpServlet {
...
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
...
// make request to Web API and save received user name to response
...
}
Details
We have web-app (.NET, MVC5) that is used TIBCO Spotfire 7.0 as engine of analysis reports.
To allow our users to see reports inside web-app we use Spotfire WebPlayer (IIS web app) and JavaScript API. We authenticate our users in web app and then they are allowed to get request to WebPlayer leveraging JS API. In order to use already authenticated users we implemented custom authentication at WebPlayer based on keys-tickets as described here. Thus we created .NET assembly that is loaded by Spotfire WebPlayer and calls overridden function. In this function we call Web API service to validate user and get valid spotfire username, then I create IIdentity with received username.
When new version of TIBCO Spotfire 7.5 released we discovered that they removed support of custom authentication, because they changed architecture and now they support "external authentication". This approach could be implemented as as Java servlet that is used to authenticate user and then spotfire:
Retrieves the user name from the getUserPrincipal() method of
javax.servlet.http.HttpServletRequest
All this forced us to re-write our logic in Java. However we don't want to change overall workflow of our authentication and we want to stick to already working ticketing schema. I'm new to Java servlets, so my goal to implement the same authentication based on servlet. They have example where servlet class has methods doGet and doPost (link to zip with example). My assumption here that I can implement my own doGet and send request to Web API to validate ticket and get back username.
Does it make sense ?
Finally I end up with this code. I implemented simple filter instead of servlet.
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import java.io.*;
import org.json.*;
public class Authenticator implements IAuthenticator {
#Override
public IIdentity doAuthentication(String pathToAuthIdentity) throws IOException {
try {
// Create an instance of HttpClient.
HttpClient httpClient = HttpClients.createDefault();
// Create a method instance.
HttpGet get = new HttpGet(pathToAuthIdentity);
HttpResponse response = httpClient.execute(get);
int internResponseStatus = response.getStatusLine().getStatusCode();
if(200 == internResponseStatus)
{
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
String userName = null;
try {
JSONObject obj = new JSONObject(result.toString());
userName = obj.getString("SpotfireUser");
} catch (JSONException ex) {
}
return new Identity(userName);
}else
{
return new AIdentity(null);
}
} catch (IOException ex) {
throw ex;
}
}
public class AIdentity implements IIdentity
{
private final String UserName;
public AIdentity(String userName)
{
this.UserName = userName;
}
#Override
public String getName() {
return UserName;
}
}
}
And that's how I use this class
import java.io.IOException;
import java.security.Principal;
import javax.servlet.http.*;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class SpotfireAuthFilter implements Filter {
private static final String AUTHENTICATION_SERVICE_URL_PARAM = "AUTHENTICATION_SERVICE_URL";
private static final String COOKIE_NAME_PARAM = "COOKIE_NAME";
private ServletContext context;
private String[] SpotfireTicketNames = null;
private String[] AuthServiceBaseURLs = null;
private IAuthenticator AuthService;
#Override
public void init(FilterConfig fc) throws ServletException {
context = fc.getServletContext();
if(null == fc.getInitParameter(AUTHENTICATION_SERVICE_URL_PARAM)
|| null == fc.getInitParameter(COOKIE_NAME_PARAM) )
{
throw new ServletException("Can't read filter initial parameters");
}
AuthServiceBaseURLs = fc.getInitParameter(AUTHENTICATION_SERVICE_URL_PARAM).split(",");
SpotfireTicketNames = fc.getInitParameter(COOKIE_NAME_PARAM).split(",");
AuthService = new Authenticator();
if(SpotfireTicketNames.length != AuthServiceBaseURLs.length)
{
throw new ServletException(
String.format("Count of '%s' parameter don't equal '%s' parameter",
COOKIE_NAME_PARAM,
AUTHENTICATION_SERVICE_URL_PARAM));
}
}
#Override
public final void doFilter(
ServletRequest servletRequest,
ServletResponse servletResponse,
FilterChain chain) throws ServletException
{
final HttpServletRequest request = (HttpServletRequest) servletRequest;
final HttpServletResponse response = (HttpServletResponse) servletResponse;
try
{
doFilter(request, response, chain);
}
catch (IOException | RuntimeException e)
{
// Not possible to authenticate, return a 401 Unauthorized status code without any WWW-Authenticate header
sendError(response, 401, "Unauthorized");
}
}
#Override
public void destroy() {
// do nothing
}
private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException
{
String url = getAuthServiceURL(request);
if(null != url)
{
IIdentity identity = AuthService.doAuthentication(url);
if(null != identity)
{
String userName = identity.getName();
if(null != userName && !userName.equalsIgnoreCase(""))
{
Principal principal = createPrincipal(userName);
// Pass on the request to the filter chain and the authentication framework
// should pick up this priincipal and authenticate user
chain.doFilter(new WrappedHttpServletRequest(request, principal), response);
}
else
{
throw new IOException("Authentication failed");
}
}else
{
throw new IOException("Can't authenticate user by url " + url);
}
}
else
{
throw new IOException("Can't find ticket to authenticate user.");
}
// Done!
return;
}
private void sendError(HttpServletResponse response, int statusCode, String message) {
try {
response.sendError(statusCode, message);
} catch (IOException e) {
}
}
private String getAuthServiceURL(HttpServletRequest request) {
Cookie[] cookies = request.getCookies();
for(int i =0; i< cookies.length; ++i)
{
for(int j =0; j< SpotfireTicketNames.length; ++j)
{
if(cookies[i].getName().equalsIgnoreCase(SpotfireTicketNames[j]))
{
return String.format(AuthServiceBaseURLs[j], cookies[i].getValue());
}
}
}
return null;
}
private Principal createPrincipal(String username)
{
// check does username contain domain/email/display name
return new APrincipal(username);
}
/**
* A wrapper for {#link HttpServletRequest} objects.
*/
private static class WrappedHttpServletRequest extends HttpServletRequestWrapper {
private final Principal principal;
public WrappedHttpServletRequest(HttpServletRequest request, Principal principal) {
super(request);
this.principal = principal;
}
#Override
public Principal getUserPrincipal() {
return this.principal;
}
} // WrappedHttpServletRequest
}
public class APrincipal implements Principal {
private final String _username;
public APrincipal(String username) {
_username = username;
}
#Override
public String getName() {
return _username;
}
}
And these initial parameters
You can use the library Apache HTTP Components
Short example for doGet() (I didn't compile it):
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
{
String url="http://your.server.com/path/to/app?par1=yxc&par2=abc");
HttpGet get=new HttpGet(url);
httpClient = HttpClients.createDefault();
// optional configuration
RequestConfig config=RequestConfig.custom().setSocketTimeout(socketTimeoutSec * 1000).build();
// more configuration
get.setConfig(config);
CloseableHttpResponse internResponse = httpClient.execute(get);
int internResponseStatus = internResponse.getStatusLine().getStatusCode();
InputStream respIn = internResponseEntity.getContent();
String contentType = internResponseEntity.getContentType().getValue();
// consume the response
}

Categories