Can anybody describe me how to use single sign-on SAML authentication in my weblogic application?
I can't use default SSO configuration because I need to do some custom checks before authenticate user. Now I use custom form auth:
public String login() {
//Some my checks...
HttpServletRequest request =
(HttpServletRequest)((ServletRequest)ADFContext.getCurrent().getEnvironment().getRequest());
CallbackHandler handler =
new SimpleCallbackHandler(username, password);
Subject subject;
try {
subject = Authentication.login(handler);
ServletAuthentication.runAs(subject, request);
ServletAuthentication.generateNewSessionID(request);
} catch (LoginException e) {
handleException(e, "Введен некорректный логин или пароль");
return "fail";
}
//Some other checks
return "success"
}
I would like to write something like this:
public String login() {
if (isSSOEnabled) {
//DO SOMETHING TO USE SSO
} else {
//do form-based auth
}
}
I use weblogic 10.3.6 and AD with Kerberos.
Related
My goal is to authenticate the WebSocket CONNECT frame. I wish to be able to initialize Authentication user = ... by using X-Auth-Token.
TL:DR
I use the X-Auth-Token header. How the current authentication works:
User hit POST /login endpoint with Form Data username and password.
The response header will contain the key X-Auth-Token.
If you hit any REST endpoint with X-Auth-Token the server will recognize the user.
The issue is how to get Authentication from X-Auth-Token in the WebSocket CONNECT frame.
The current solution is to use JWT, however, one of the requirements for this project is a user should be able to invalidate the session. For JWT to be able to do that, the JWT should be a stateful, reference to this SO's the question
#Configuration
#EnableWebSocketMessageBroker
// see: https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#websocket-stomp-authentication-token-based
#Order(Ordered.HIGHEST_PRECEDENCE + 99)
public class WebSocketAuthenticationConfig implements WebSocketMessageBrokerConfigurer {
#Override
public void configureClientInboundChannel(ChannelRegistration registration) {
registration.interceptors(new ChannelInterceptor() {
#Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
StompHeaderAccessor accessor =
MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
if (StompCommand.CONNECT.equals(accessor.getCommand())) {
String sessionId = accessor.getFirstNativeHeader("X-AUTH-TOKEN");
// Authentication user; // How to get Authentication from X-Auth-Token?
// accessor.setUser(user);
}
return message;
}
});
}
}
What I did:
I change Cookie-based authentication by letting the session be provided in a header.
// see: https://docs.spring.io/spring-session/docs/current/reference/html5/#httpsession-rest
#Configuration
// Override HttpSession's Filter, in this instance Spring Session is backed by Redis.
#EnableRedisHttpSession
public class HttpSessionConfig {
// Default connection configuration, to localhost:6739.
#Bean
public LettuceConnectionFactory connectionFactory() {
return new LettuceConnectionFactory();
}
// Tell Spring to use HTTP headers, X-Auth-Token.
#Bean
public HttpSessionIdResolver httpSessionIdResolver() {
return HeaderHttpSessionIdResolver.xAuthToken();
}
}
logic to CONNECT and SUBSCRIBE
const X-Auth-Token = "" // get from the POST `/login` endpoint
const onConnectCallback = () => {
const destinations = ["/topic/channel/1", "/user/queue/messages"];
for (let i = 0; i < destinations.length; i++) {
stompClient.subscribe(destinations[i], (payload) => {
// receiveMessageCallback
});
}
};
const stompConfig = {
brokerURL: "ws://localhost:8080/chat",
connectHeaders: {
"X-Auth-Token": X_Auth_Token,
},
onConnect: onConnectCallback,
};
const stompClient = new StompJs.Client(stompConfig);
stompClient.activate();
Reference
I am worried that X-Auth-Token is not supported in WebSocket because based on SO's answer there is no API to retrieve session by id
I'm trying to secure my rest services written using dropwizard by Apache Shiro. First I initialized the security manager in the main method.
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
Then I wrote a service for user login.
if (!currentUser.isAuthenticated()) {
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
token.setRememberMe(true);
try {
currentUser.login(token);
System.out.println("USER AUTHENTICATED!!!!!!!!");
} catch (Exception uae) {
System.out.println("Error logging in .................");
}
}
Then I declared a method with some java annotations.
#RequiresAuthentication
#RequiresRoles("admin")
#GET
#Path("/account")
#ApiOperation(value = "getAccount")
public void getAccount() {
//do something
}
But when I accessed this resource without logging in, I was successful.
What mistake am I doing? Or should I add something more? Like in the web.xml?
I found this repo very useful. https://github.com/silb/dropwizard-shiro/tree/release-0.2. I followed the instructions given in this. But there is one more thing I added in the configuration file.
#Valid
#JsonProperty("shiro-configuration")
public ShiroConfiguration shiro = new ShiroConfiguration();
Then in the resources class, I wrote login and logout as two services.
#POST
#Path("/session")
#Produces(MediaType.TEXT_PLAIN)
public String login(#FormParam("username") String username, #FormParam("password") String password, #Auth Subject subject) {
subject.login(new UsernamePasswordToken(username, password));
return username;
}
#PUT
#Path("/logout")
#Produces(MediaType.TEXT_PLAIN)
public String logout(#Auth Subject subject){
subject.logout();
return "Successfully logged out!";
}
And then I annotated the secured resources with #RequiresAuthentication annotation.
I have this very basic authentication for my app:
MapVerifier mapVerifier = new MapVerifier();
mapVerifier.getLocalSecrets().put("user", "pass".toCharArray());
ChallengeAuthenticator guard= new ChallengeAuthenticator(null, ChallengeScheme.HTTP_BASIC, "Secured Resources");
guard.setContext(getContext());
guard.setVerifier(mapVerifier);
How do I adapt this to use Google authentication scheme? That, instead of showing the Username/Password browser popup, it will go to the Google authentication page.
I think that you aren't in the context of a challenge authentication and you need to leverage the authentication service of Google.
Here is an implementation of this approach (not tested) if you want a custom Restlet Authenticator implementation:
public class GoogleAuthenticator extends Authenticator {
private UserService userService;
public GoogleAuthenticator(Context context) {
super(context);
this.userService = UserServiceFactory.getUserService();
}
protected User createUser(com.google.appengine.api.users.User googleUser,
Request request, Response response) {
return new User(googleUser.getUserId());
}
protected boolean authenticate(Request request, Response response) {
// Get current Google user
com.google.appengine.api.users.User googleUser = userService.getCurrentUser();
// Check if the user is authenticated
if (googleUser!=null) {
// Authenticated through Google authentication service
request.getClientInfo().setUser(
createUser(googleUser, request, response));
return true;
} else {
// Not authenticated. Redirect to the login URL
response.redirectSeeOther(userService.createLoginURL(
request.getRequestURI()));
return false;
}
}
}
However such authenticator exists in the extension org.restlet.ext.gae for a while. It leverages the service UserService of GAE. So I think that you have it with the version of Restlet you use. Here is a sample of use below:
public Restlet createInboundRoot() {
Router router = new Router(getContext());
(...)
GaeAuthenticator guard= new GaeAuthenticator(getContext());
guard.setNext(router);
return guard;
}
Edited:
You can notice that the GAE authenticator can use the GAE enroler for this purpose (i.e. if it's an admin one).
To implement this, you simply need to instantiate such enroler and set it on your authenticator, as desribed below:
GaeEnroler enroler = new GaeEnroler();
GaeAuthenticator guard = new GaeAuthenticator(getContext());
guard.setEnroler(enroler)
guard.setNext(router);
Within your server resource, you can then check the role, as described below:
protected boolean hasAdminRole() {
ClientInfo clientInfo = getClientInfo();
List<Role> roles = clientInfo.getRoles();
boolean isAdmin = false;
for (Role role : roles) {
if (role.getName().equals("admin")) {
isAdmin = true;
break;
}
}
return isAdmin;
}
#Post
public XX handlePost(YY content) {
if (!hasAdminRole()) {
throw new ResourceException(Status.CLIENT_ERROR_FORBIDDEN);
}
(...)
}
Hope it helps you,
Thierry
I haven't fully understood what's ur question is ? If u wanted to integrate Google authentication in yours system check the link
google Oauth2
It's not depend upon any framework it's simply redirection and callback which u can do with plain servlets , obviously you can do with restlets too
I have written an simply library to integrate google and Facebook oauth 2, you can check this to see how it works
java oauth2 gae
I am creating a Spring MVC web application using spring security for authentication.
My application has a requirement that the user is logged in automatically when the user accesses a particular URL, say http://www.example.com/login?username=xyz
The user xyz is in the database, and I need to create a session for this user automatically.
Request you to let me know how this can be achieved.
Thanks!
You can do something like this, the idea would be to retrieve the user from the database, make the checks you want and then use the UsernamePasswordAuthenticationToken to create a new Principal into the current session.
The use of the returned Principal of the method is for subsequent uses on the same request, as the Principal won't be available to be retrieved by normal means until the next request.
public Principal doAutoLogin(String username, String password, HttpServletRequest hreq, HttpServletResponse hres, boolean rememberMe) {
User user = getUserFromDatabase(username);
if(user != null && passwordsMatch(password, user.getPassword())) {
try {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
token.setDetails(new WebAuthenticationDetails(hreq));
if(LOG.isDebugEnabled())
LOG.debug("Logging in with "+ token.getPrincipal());
SecurityContextHolder.getContext().setAuthentication(token);
if(rememberMe) {
rememberMeServices.onLoginSuccess(hreq, hres, token);
}
return token;
} catch (Exception e) {
SecurityContextHolder.getContext().setAuthentication(null);
LOG.error("Failure in autoLogin", e);
return null;
}
}
else {
throw new IllegalArgumentException("The specified credentials can't be found");
}
}
I want to develop a SOAP client using CXF to connect to SharePoint. The authentication scheme is NTLM.
I am blocked on a scenario where the logged-in user of a machine (on which the SOAP client is being run) has access to SharePoint. The CXF soap client always uses the logged-in user. I want to specify some other user credentials (not the logged-in).
As CXF uses in-JDK HttpURLConnection; and what I have read about HttpURLConnection is, it bypasses the specified credentials when the logged-in user is NTLM authenticated.
Codes were tried on CXF version 2.7.11.
Solutions that I have tried out:
1) Setting Conduit authorization
String username = "user";
String password = "password";
JaxWsProxyfactoryBean factory1 = new JaxWsProxyfactoryBean();
factory1.setServiceClass(WebsSoap.class);
factory1.setAddress(url);
factory1.setUsername(username);
factory1.setPassword(password);
WebsSoap service = (WebsSoap) factory1.create();
Client client = ClientProxy.getClient(service);
HTTPconduit conduit = (HTTPconduit) client.getconduit();
conduit.getAuthorization().setAuthorizationType("NTLM");
conduit.getAuthorization().setUserName(username);
conduit.getAuthorization().setPassword(password);
HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
httpClientPolicy.setConnectionTimeout(36000);
httpClientPolicy.setAllowChunking(false);
conduit.setClient(httpClientPolicy);
service.getWeb(".");
Problem:
This does not work for the scenario specified above, as it always uses the logged-in credentials. And when I specify invalid credentials, it does not fail.
2) AsyncHTTPConduit
Another solution is to use AsyncHTTPConduit that uses HttpAsyncClient instead of HttpURLConnection. This is beacuse HTTP components do not bypass specified credentials and logged-in user can be ignored (I have successfully verified this with a test client using HttpClient).
Below is the code snippet::
Bus bus = BusFactory.getDefaultBus();
bus.setProperty( "use.async.http.conduit", "true" );
Client client = ClientProxy.getClient( service );
HTTPConduit http = (HTTPConduit)client.getConduit();
if ( http instanceof AsyncHTTPConduit ) {
AsyncHTTPConduit conduit = (AsyncHTTPConduit)http;
DefaultHttpAsyncClient defaultHttpAsyncClient;
try {
defaultHttpAsyncClient = conduit.getHttpAsyncClient();
}
catch ( IOException exception ) {
throw new RuntimeException( exception );
}
defaultHttpAsyncClient.getCredentialsProvider().setCredentials( AuthScope.ANY,
new NTCredentials( "username", "password", "", "domain" ) );
conduit.getClient().setAllowChunking( false );
conduit.getClient().setAutoRedirect( true );
}
Problem:
Above code throws error:
Authorization loop detected on conduit.
The above code snapshot shows the usage of DefaultHttpAsyncClient which is deprecated now and CloseableHttpAsyncClient is to be used instead. But CloseableHttpAsyncClient does not provide a way to specify credentials to an already existing CloseableHttpAsyncClient object. Not sure how to use CloseableHttpAsyncClient in this scenario.
3) Other solutions
The other solution that I tried out is to use sun.net.www.protocol.http.ntlm.NTLMAuthenticationCallback, to bypass logged-in user authentication, as mentioned here. Use this approach along with solution #1 mentioned above. This works as expected for valid/invalid credentials, and the code bypasses the logged-in credentials :). But when I specify invalid credentials, I do not get HTTP 401 error, instead I get
Could not send message, server reached max retries 20
I am trying to avoid this solution because it uses java’s internal package and there is no way to determine HTTP 401 error directly.
What can I do to arrive at a complete solution?
Try this interceptor. This will avoid automatic authentication.
public class DisableAutomaticNTLMAuthOutInterceptor extends AbstractPhaseInterceptor<Message>
{
private boolean isFieldsAvailable;
private Field tryTransparentNTLMProxyField;
private Field tryTransparentNTLMServerField;
public DisableAutomaticNTLMAuthOutInterceptor() {
super(Phase.PRE_STREAM);
AccessController.doPrivileged(new PrivilegedAction<Object>() {
public Void run() {
try {
DisableAutomaticNTLMAuthOutInterceptor.this.tryTransparentNTLMServerField = HttpURLConnection.class.getDeclaredField("tryTransparentNTLMServer");
DisableAutomaticNTLMAuthOutInterceptor.this.tryTransparentNTLMServerField.setAccessible(true);
DisableAutomaticNTLMAuthOutInterceptor.this.tryTransparentNTLMProxyField = HttpURLConnection.class.getDeclaredField("tryTransparentNTLMProxy");
DisableAutomaticNTLMAuthOutInterceptor.this.tryTransparentNTLMProxyField.setAccessible(true);
DisableAutomaticNTLMAuthOutInterceptor.this.isFieldsAvailable = true;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
});
}
#Override
public void handleMessage(final Message message) throws Fault {
if (this.isFieldsAvailable)
AccessController.doPrivileged(new PrivilegedAction<Object>() {
public Void run() {
try {
Object httpConnection = message.get("http.connection");
if (httpConnection != null) {
DisableAutomaticNTLMAuthOutInterceptor.this.processHttpConnection(message.get("http.connection"));
}
} catch (Throwable t) {
t.printStackTrace();
}
return null;
}
});
}
private void processHttpConnection(Object httpConnection) throws IllegalArgumentException, IllegalAccessException {
if (HttpURLConnection.class.isAssignableFrom(httpConnection.getClass())) {
tryTransparentNTLMServerField.set(httpConnection, Boolean.FALSE);
tryTransparentNTLMProxyField.set(httpConnection, Boolean.FALSE);
} else {
Field tempField = null;
for (Field field : httpConnection.getClass().getDeclaredFields()) {
if (HttpURLConnection.class.isAssignableFrom(field.getType())) {
field.setAccessible(true);
tempField = field;
break;
}
}
if (tempField != null) {
processHttpConnection(tempField.get(httpConnection));
}
}
}
}