Does spring-boot-admin support sso? - single-sign-on

I'm trying to integrate spring-boot-admin with my corporate SSO, does spring-boot-admin support sso login? I cannot find documentation about it.

I got it to work. Steps to implement:
Create controller with an endpoint that the sso provider will call.
In the endpoint, put the logic for sso integration,
On success, redirect to /applications
On failure, throw an exception
#Controller
public class SsoIntegration {
// this does addition authentication stuff, like sets up the
// right authorities...etc
#Autowired
private AuthenticationProvider authenticationProvider;
// my sso provider creates a vanity url that redirects to
// this endpoint and passes 2 request params using POST
#RequestMapping(value={"/sso"}, method = {RequestMethod.POST})
public String ssologin (
#RequestParam(name="param1") String param1,
#RequestParam(name="param2") String param2 )
{
// do your sso integration logic here
// eg...
SsoUtil util = new SsoUtil();
String userInfo = util.decrypt(param1, param2, ...);
...
if (authenticationProvider.authenticate( userInfo )) {
Authentication postAuthentication = ...// populate your successfully authenticated user
// these next lines are the important stuff
// 1. set the postAuthentication into the security context
SecurityContextHolder.getContext().setAuthentication(postAuthentication);
// 2. redirect to the applications page
return "redirect:/applications";
}
// authentication failed, throw an exception...
throw new RuntimeException ("Sso Authentication failed");
}
}

Related

ITfoxtec.Identity.Saml2 - Multiple authentication schemes with Asp.net Core Identity

I am aware of the answer given here which is about using Forms Authentication & SAML. In My case I am using Asp.net core Identity on .Net 5. Also I am using two authentication schemes (Cookies & JWT).
My auth pipeline goes as;
//include identity
services.AddIdentity<ApplicationUser, ApplicationRole>(SetupIdentityOptions)
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
//configure cookie and Jwt scheme
services.ConfigureApplicationCookie(...)
services.AddAuthentication(...) //configures default Identity
.AddJwtBearer(options => {...})
services.AddAuthorization(options =>
{
options.FallbackPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
});
What I want to know is where should I add SAML2 in this pipeline.
In general the application should;
Be able to login with Cookie authentication (Identity takes care of this)
Jwt tokens should work as well for Apis (this also works with Jwt scheme)
SSO clients should get authenticated from their IdP and when redirected to AssertionConsumer() I will create additional claims create new ClaimsIdentity, create a JWT token(pass it to client) and get the user to dashboard.
I am stuck at 3rd point which is to properly add the SAML scheme without overriding cookie/jwt schemes.
The error No sign-in authentication handler is registered for the scheme 'saml2' probably occurs bedause you need to add services.AddSaml2() and app.UseSaml2()
You can use the setup from the provided example project. Newly added middleware should not interfere with what you already have.
When a SAML2 IdP redirects back to your application, you are given a result that identifies the authenticated user, e.g. Email Address or SSN (in case it is a government Id Provider).
You can combine that information with a Role (e.g. SpecialCustomer, Citizen, or an existing Role that you already have) into a cookie or JWT Token as you probably already do for other users. This can always be distinguished from other cookies and tokens by the Role. Regular [Authorize(....)] attributes will also work just fine.
I was stuck at the same point.. The solution I found:
If you check the source code of IFOXTEC.IDENTITY.SAML2, the method AddSaml2 overrides your AddAuthentication method and adds the AddCookie section.
public static IServiceCollection AddSaml2(this IServiceCollection services, string loginPath = "/Auth/Login", bool slidingExpiration = false, string accessDeniedPath = null, ITicketStore sessionStore = null, SameSiteMode cookieSameSite = SameSiteMode.Lax, string cookieDomain = null, CookieSecurePolicy cookieSecurePolicy = CookieSecurePolicy.SameAsRequest)
{
services.AddAuthentication(Saml2Constants.AuthenticationScheme)
.AddCookie(Saml2Constants.AuthenticationScheme, o =>
{
o.LoginPath = new PathString(loginPath);
o.SlidingExpiration = slidingExpiration;
if(!string.IsNullOrEmpty(accessDeniedPath))
{
o.AccessDeniedPath = new PathString(accessDeniedPath);
}
if (sessionStore != null)
{
o.SessionStore = sessionStore;
}
o.Cookie.SameSite = cookieSameSite;
o.Cookie.SecurePolicy = cookieSecurePolicy;
if (!string.IsNullOrEmpty(cookieDomain))
{
o.Cookie.Domain = cookieDomain;
}
});
return services;
}
So, to add SAML to your pipeline, you can remove the services.AddSaml2(), add the AddCookie section and, inside your policy, you can add the verification of any cookie with name saml2 to forward to your SAML schema.
services
.AddAuthentication(sharedOptions =>
{
sharedOptions.DefaultScheme = "custom-schema";
sharedOptions.DefaultChallengeScheme = "custom-schema";
})
.AddPolicyScheme("custom-schema", null, options =>
{
options.ForwardDefaultSelector = context =>
{
if (context.Request.Headers["Authorization"].Any(x => x.StartsWith("Bearer ")))
return JwtBearerDefaults.AuthenticationScheme;
else if (context.Request.Headers["Cookie"].Any(x => x.Contains(".saml2=")))
return Saml2Constants.AuthenticationScheme;
return "Identity.Application";
};
})
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, null, options =>
{
//...
})
.AddCookie(Saml2Constants.AuthenticationScheme, o =>
{
o.LoginPath = new PathString("/Auth/Login");
o.SlidingExpiration = false;
o.Cookie.SameSite = SameSiteMode.Lax;
o.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
});

How to obtain an access token within a Keycloak SPI?

Use case:
From inside a EventListenerProvider on an event I want to make an authenticated REST call to one of our keycloak secured service. For this I need a token.
First I just test printing the token to check whether it is succeeded.
public void onEvent(final Event event) {
Keycloak k = Keycloak.getInstance("http://localhost:8080/auth", "myrealm", "myemail#gmail.com", "password", "myclient");
AccessTokenResponse t = k.tokenManager().getAccessToken();
logger.info(t.getSessionState());
logger.info(t.getToken());
}
Unfortunatly both the session_state and token is NULL.
All the data are correct, the url,the realm..etc. Otherwise we would know about that. Keycloak doesnt log anything just silently returns null.
On the top of that I can use the above code from anywhere else and it works! I can use it from a plain java main() method and still works. Getting token by hand via postman also works.
What is wrong with the Keycloak Provider? How can I get an accesstoken for a particular user?
You can use the following example to create a AccessToken:
public String getAccessToken(UserModel userModel, KeycloakSession keycloakSession) {
KeycloakContext keycloakContext = keycloakSession.getContext();
AccessToken token = new AccessToken();
token.subject(userModel.getId());
token.issuer(Urls.realmIssuer(keycloakContext.getUri().getBaseUri(), keycloakContext.getRealm().getName()));
token.issuedNow();
token.expiration((int) (token.getIat() + 60L)); //Lifetime of 60 seconds
KeyWrapper key = keycloakSession.keys().getActiveKey(keycloakContext.getRealm(), KeyUse.SIG, "RS256");
return new JWSBuilder().kid(key.getKid()).type("JWT").jsonContent(token).sign(new AsymmetricSignatureSignerContext(key));
}
Note that you also need to specify <module name="org.keycloak.keycloak-services"/> in your jboss-deployment-structure.

IdentityServer3 Guidance Needed

I have a scenario where a client has an OpenIdConnect (OIDC) token in their possession. The OIDC was issued from an external OIDC provider, I am not the OIDC provider, just the downstream consumer of it.
The goal is for the client to exchange said OIDC Token, for temporary credentials, or an accesstoken, which will then give them api access to more specific resources.
In my case, the OIDC represents a user. The client, has a ClientId/Secret, which is used to establish service-2-service trust. In the end I would like to have something that looks a lot like the CustomGrant token Request.
static TokenResponse GetCustomGrantToken()
{
var client = new TokenClient(
token_endpoint,
"custom_grant_client",
"cd19ac6f-3bfa-4577-9579-da32fd15788a");
var customParams = new Dictionary<string, string>
{
{ "some_custom_parameter", "some_value" }
};
var result = client.RequestCustomGrantAsync("custom", "read", customParams).Result;
return result;
}
where my customParams would contain the OIDC to my user.
Problem: I can get a token back from the GetCustomGrantToken call, however a follow up Webapi call fails to pass Authorization. i.e. Identity.isAuthenticated is false.
The it all works fine if I get a clientcredential token.
static TokenResponse GetClientToken()
{
var client = new TokenClient(
token_endpoint,
"silicon",
"F621F470-9731-4A25-80EF-67A6F7C5F4B8");
return client.RequestClientCredentialsAsync("api1").Result;
}
Had the CustomGrantToken worked I would have put my users account info in the claims, thus giving me context in the subsequent WebApi calls.
Any direction would be appreciated.

Spring Security and social SignUp with Rest

My application exposes a REST API for services and uses SpringSecurity to manage login at the private services.
With custom signup and login I don't have any kind of problem, but now I try to implement login/signup with Facebook or Twitter, and I don't know how to do this.
Has anyone had the same problem and solved it?
I tried to use a custom password "very long" for every Facebook and Twitter account but that didn't work.
UPDATE
I try your solution, but get an error. This is my code
public UserDetails loadUserByUsername(String mail) throws UsernameNotFoundException {
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
if (ConstantPWCabinet.SOCIAL_LOGIN_FACEBOOK.equalsIgnoreCase(attr.getRequest().getParameter(ConstantPWCabinet.LOGIN_TYPE))) {
User facebookInfo = dao.getFacebookInfo(new FacebookTemplate(attr.getRequest().getParameter(ConstantPWCabinet.FACEBOOK_TOKEN)));
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
authorities.add(new SimpleGrantedAuthority(Role.ROLE_USER_FACEBOOK.toString()));
org.springframework.security.core.userdetails.User user = new org.springframework.security.core.userdetails.User(facebookInfo.getEmail(), null, authorities);
Authentication auth = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(auth);
return user;
}
logger.debug("Mail di accesso: " + mail);
User user = dao.getUserSelectedMail(mail);
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
String role = user.getRole().toString();
if (StringUtils.isEmpty(role))
authorities.add(new SimpleGrantedAuthority(Role.ROLE_USER.toString()));
else
authorities.add(new SimpleGrantedAuthority(role));
return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(), authorities);
}
But i get and "Bad credential" and no get login.
You have an AuthenticationFilter that listens to url j_spring_security_check
Filter creates an authentication object and sends to Authentication Provider.
AuthenticationProvider calls UserDetailsService to load user by username and authenticate the user.
Filter then checks the authentication object returned by the provider and sends request to success/failure handler.
When you do it through social medium, your user is authenticated by an external source, so you do not need to authenticate user at your end.
You can simple do
// Authenticate the user
UserDetails user = userDetailsService.loadUserByUsername(username);
Authentication auth = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(auth);
This will authenticate the user without password.

ServiceStack OAuth - registration instead login

In servicestack OAuth implementation I only saw possibility to automatically login with eg. facebook account.
But is there abbility to support registration process with facebook login. What I wanted is to let users login to facebook app, and then load their Name, Surname and email and prefill needed text boxes for real registration on my site (since I also have to have mobile phone verification etc.) I don't want user to be authorized and authenticated when he logs in with facebook. Only credentials login should be valid one for full site access.
Edit: I found a solution.
In FacebookProvider.cs
public override bool IsAuthorized(IAuthSession session, IOAuthTokens tokens, Auth request = null)
{
if (request != null)
{
if (!LoginMatchesSession(session, request.UserName)) return false;
}
return tokens != null && session.UserName!=null && !string.IsNullOrEmpty(tokens.AccessTokenSecret);
}
The catch was the && session.UserName!=null part. So we can check if user is logged in using credentials, this will be !=null and user can use all services. If not, this will be ==null and he can only get facebook info from session.
The SocialBootstrap API project shows an example of handling the callback after a successful Authentication by overriding the OnAuthenticated() hook of its custom user session:
I've pulled out, rewrote some and highlighted some of the important bits:
public class CustomUserSession : AuthUserSession
{
public override void OnAuthenticated(IServiceBase authService,
IAuthSession session,
IOAuthTokens tokens,
Dictionary<string, string> authInfo)
{
base.OnAuthenticated(authService, session, tokens, authInfo);
//Populate matching fields from this session into your own MyUserTable
var user = session.TranslateTo<MyUserTable>();
user.Id = int.Parse(session.UserAuthId);
user.GravatarImageUrl64 = CreateGravatarUrl(session.Email, 64);
foreach (var authToken in session.ProviderOAuthAccess)
{
if (authToken.Provider == FacebookAuthProvider.Name)
{
user.FacebookName = authToken.DisplayName;
user.FacebookFirstName = authToken.FirstName;
user.FacebookLastName = authToken.LastName;
user.FacebookEmail = authToken.Email;
}
else if (authToken.Provider == TwitterAuthProvider.Name)
{
user.TwitterName = authToken.DisplayName;
}
}
//Resolve the DbFactory from the IOC and persist the user info
using (var db = authService.TryResolve<IDbConnectionFactory>().Open())
{
//Update (if exists) or insert populated data into 'MyUserTable'
db.Save(user);
}
}
//Change `IsAuthorized` to only verify users authenticated with Credentials
public override bool IsAuthorized(string provider)
{
if (provider != AuthService.CredentialsProvider) return false;
return base.IsAuthorized(provider);
}
}
Basically this user-defined custom logic (which gets fired after every successful authentication) extracts data from the UserSession and stores it in a custom 'MyUserTable'.
We've also overridden the meaning of IsAuthorized to only accept users that have authenticated with CredentialsAuth.
You can use this data to complete the rest of the registration.
Other possible customizations
ServiceStack's built-in Auth persists the AuthData and populates the Session automatically for you. If you want to add extra validation assertions you can simply use your own custom [Authentication] attribute instead containing additional custom logic. Look at the implementation of the built-in AuthenticateAttribute as a guide.