Only allow 1 user login in Spring Sercurity - spring-mvc

I have two users: A and B, if user A login first, user B cant login util user A logout. Each user require three login info: storeId, storePassword, userPassword.
If user B same storeId with user A, do not allow login
If user B different storeId with user A, allow login
I use ServletContext to hold users logged, and when logged user click logout, I will remove that user from ServletContext. But I cant hanle when user close brower intead of click logout. I think this is not a good idea
Here is my code
#Override
public void onLogoutSuccess(HttpServletRequest request,
HttpServletResponse response, Authentication authentication)
throws IOException, ServletException {
//redirectStrategy.sendRedirect(request, response, "/login");
// do whatever you want
ServletContext context = request.getSession().getServletContext();
Object _auths = context.getAttribute("_authentications");
if(_auths != null) {
List<String> auths = (List<String>) _auths;
auths.remove(authentication.getName());
if(auths.size() == 0) {
auths = new ArrayList<String>();
}
context.setAttribute("_authentications", auths);
}
super.onLogoutSuccess(request, response, authentication);
}
does anyone give me a good solution?
Thank you

i have solved my problem, i use SessionRegistry in AuthencationProvide intead of ServletContext
#Autowired
#Qualifier("sessionRegistry")
private SessionRegistry sessionRegistry;
List<Object> principals = sessionRegistry.getAllPrincipals();
for (Object principal: principals) {
String[] auths = principal.toString().split(StringPool.DASH);
if(auths.length == 4 && auths[1].equals(storeId)) {
throw new BadCredentialsException(auths[0]+StringPool.DASH+auths[1]);
}
}
this code work well when session time out, user close brower. And i dont need any js source code to handle

You can use the js below to remove user from servletContext on window close:
<script type="text/javascript">
window.onbeforeunload = logout;
function logout(){
// Make an ajax call to remove user from ServletContext
alert("Window close is being called");
return false;
}
</script>

Related

AADSTS50059: No tenant-identifying information found when acquiring the code using "{prompt", "none"}"

So I use ADAL library to get id token.
I got the code sample from here
sample code
However, if I set the query string prompt to none. I would get this annoying message AADSTS50059: No tenant-identifying information found in either the request or implied by any provided credentials. If the user is not logged in when getting the code. And the screen will hang in the Microsoft login window.
I need to set it as "prompt", "consent" so even not logged in the user can still perform sign in/consent. But I wan to simply the process, not to get the user go through this sign in/consent every time.
Is there a way to do it so that for not already sign in user an call back error is returned instead of this error and hanging there forever?
According to the doc, {prompt", "none"} should be a valid configuration.
I copy the sample code here for convenient purpose:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Params["code"] != null)
{
var accesstoken = AcquireTokenWithResource(resource: "https://graph.microsoft.com/");
Response.Write(accesstoken);
}
}
protected void Button2_Click(object sender, EventArgs e)
{
GetAuthorizationCode();
}
public void GetAuthorizationCode()
{
JObject response = new JObject();
var parameters = new Dictionary<string, string>
{
{ "response_type", "code" },
{ "client_id", "clientid" },
{ "redirect_uri", "http://localhost:8099/WebForm1.aspx" },
{ "prompt", "none"},
{ "scope", "openid"}
};
var requestUrl = string.Format("{0}/authorize?{1}", EndPointUrl, BuildQueryString(parameters));
Response.Redirect(requestUrl);
}
public string AcquireTokenWithResource(string resource)
{
var code = Request.Params["code"];
AuthenticationContext ac =
new AuthenticationContext(string.Format("https://login.microsoftonline.com/{0}", "tenantID"
));
ClientCredential clcred =
new ClientCredential("clientID", "clientSecret");
var token =
ac.AcquireTokenByAuthorizationCodeAsync(code,
new Uri("http://localhost:8099/WebForm1.aspx"), clcred,resource).Result.AccessToken;
return token;
}
private string BuildQueryString(IDictionary<string, string> parameters)
{
var list = new List<string>();
foreach (var parameter in parameters)
{
list.Add(string.Format("{0}={1}", parameter.Key, HttpUtility.UrlEncode(parameter.Value)));
}
return string.Join("&", list);
}
protected string EndPointUrl
{
get
{
return string.Format("{0}/{1}/{2}", "https://login.microsoftonline.com", "tenantID", #"oauth2/");
}
}
Can you check the detailed logs of this error. If you are you using ADAL login the it could be local storage caching issue. as when ADAL login is successful it caches the login info into your browser’s local storage to eliminate the need to log in again anytime soon but in certain situations where you will be authenticating against multiple Azure AD instances it will mix-up the authentication. To fix this you will need to clear the browser's storage cache by using the developer tools(F12) then browse to “Application” tab, and then find your tenant from the “Local Storage” -section. After removing all the storage entries for ADAL refresh the page that threw the error before and you should be greeted with a fresh login screen.
Hope it helps.

Can we add users to keycloak in realms other than 'master'?

I can add users to keycloak but only in the master realm. Is there a way to add users to other realms beside master?
I tried and received an HTTP 401 Unauthorized Exception.
Sounds like your user doesn't have the manage-users role in other realms.
Just go to the admin realm, look up your user, navigate to Role mappings tab, then in the Client Roles drop down select the correct realm and then add manage-users as a role. Repeat for all realms.
//Here's how I created a user to my realm using Java
#Override
public UserDto registerNewUserAccount(final UserDto accountDto) {
String keycloakPassword = accountDto.getPassword();
accountDto.setPassword(passwordEncoder.encode(accountDto.getPassword()));
accountDto.setEnabled(1);
UserDto user = userRepository.save(accountDto);
AuthorityDto role = new AuthorityDto();
role.setUserName(accountDto.getLogin());
role.setAuthority("ROLE_USER");
authorityRepository.save(role);
Keycloak kc = Keycloak.getInstance(
"https://www.zdslogic.com/keycloak/auth", /your server
"zdslogic", //your realm
"richard.campion", //user
"Changit", //password
"admin-cli"); //client
CredentialRepresentation credential = new CredentialRepresentation();
credential.setType(CredentialRepresentation.PASSWORD);
credential.setValue(keycloakPassword);
UserRepresentation keycloakUser = new UserRepresentation();
keycloakUser.setUsername(accountDto.getLogin());
keycloakUser.setFirstName(accountDto.getFirstName());
keycloakUser.setLastName(accountDto.getLastName());
keycloakUser.setEmail(accountDto.getEmail());
keycloakUser.setCredentials(Arrays.asList(credential));
keycloakUser.setEnabled(true);
keycloakUser.setRealmRoles(Arrays.asList("user"));
// Get realm
RealmResource realmResource = kc.realm("zdslogic");
UsersResource usersRessource = realmResource.users();
// Create Keycloak user
Response result = null;
try {
result = usersRessource.create(keycloakUser);
} catch(Exception e) {
System.out.println(e);
}
if (result==null || result.getStatus() != 201) {
System.err.println("Couldn't create Keycloak user.");
}else{
System.out.println("Keycloak user created.... verify in keycloak!");
}
return user;
}

SignInManager.SignInPasswordAsync is not logging in the User in ApiController

I have an ApiController that handles ajax login requests. Below is what is happening in the code:
// I tried with HttpContext.Current.GetOwinContext().Get... and it didn't work either
private ApplicationUserManager userManager => Request.GetOwinContext().Get<ApplicationManager>();
private ApplicationSignInManager signInManager => Request.GetOwinContext().Get<ApplicationSignInManager>();
public async Task<IHttpActionResult> Login(LoginJson request)
{
var user = await userManager.FindByEmailAsync(request.Email);
var result = await signInManager.PasswordSignInAsync(user.UserName, request.Password, true, true);
if (result == SignInStatus.Success)
{
if (!User.Identity.IsAuthenticated)
{
throw new Exception("Why are you not authenticating!!!");
}
}
return Ok();
}
That exception is always thrown (i.e. the result is Success and yet IPrincipal reports that user is not authenticated yet).
What is even weirder is that if I reload the page I am taken to the dashboard page (Dashboard is the default home page for authenticated users), meaning the previous request actually did log the user in. But then why would User.Identity.IsAuthenticated return false in my first login request? Any ideas?
Note: this is only happening for ApiController, a normal MVC Controller logs the user in correctly
Authentication cookie is only set when your controller send a reply to a client (browser). And User.Identity.IsAuthenticated is checking if the cookie is set. But you are trying to check if the cookie is set within the same request as where you set the cookie.
In other words you can only check if user is authenticated only on the following request after you call PasswordSignInAsync. So remove that throw new Exception... and you'll be fine.

Programmatically log-in a user using spring security

The opposite of: How to manually log out a user with spring security?
In my app I have register new user screen, which posts to a controller which creates a new user within db (and does a few obvious checks).I then want this new user to be automatically logged in ... I kind of want somethign like this :
SecurityContextHolder.getContext().setPrincipal(MyNewUser);
Edit
Well I have almost implemented based on the answer to How to programmatically log user in with Spring Security 3.1
Authentication auth = new UsernamePasswordAuthenticationToken(MyNewUser, null);
SecurityContextHolder.getContext().setPrincipal(MyNewUser);
However, when deployed the jsp can not access my MyNewUser.getWhateverMethods() whereas it does when normal login procedure followed. the code that works nomrally, but throws an error when logged in like above is below :
<sec:authentication property="principal.firstname" />
In my controller i have this, which logs user in as normal :
Authentication auth =
new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(auth);
Where user is my custom user object(implementing UserDetails) that is newly created. The getAuthorities() method does this (just because all my users have the same role):
public Collection<GrantedAuthority> getAuthorities() {
//make everyone ROLE_USER
Collection<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
GrantedAuthority grantedAuthority = new GrantedAuthority() {
//anonymous inner type
public String getAuthority() {
return "ROLE_USER";
}
};
grantedAuthorities.add(grantedAuthority);
return grantedAuthorities;
}
You can also inject your spring security configured UserDetailsManager to your controller and use that to get the UserDetails which holds the principal and authorities to avoid duplicate code:
// inject
#Autowired
private UserDetailsManager manager;
// use in your method
UserDetails userDetails = manager.loadUserByUsername (token.getUsername ());
Authentication auth = new UsernamePasswordAuthenticationToken (userDetails.getUsername (),userDetails.getPassword (),userDetails.getAuthorities ());
SecurityContextHolder.getContext().setAuthentication(auth);
From the spring security source AbstractAuthenticationProcessingFilter:
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
Authentication authResult) throws IOException, ServletException {
if (logger.isDebugEnabled()) {
logger.debug("Authentication success. Updating SecurityContextHolder to contain: " + authResult);
}
// you need this
SecurityContextHolder.getContext().setAuthentication(authResult);
rememberMeServices.loginSuccess(request, response, authResult);
if (this.eventPublisher != null) {
eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(authResult, this.getClass()));
}
successHandler.onAuthenticationSuccess(request, response, authResult);
}
Note however that the SecurityContextHolder is usually cleared upon completion of the filter chain.
For anyone trying to do this with Reactive Spring Security, this is what I did and it seemed to work.
private Mono<Authentication> authenticateUser(ServerWebExchange exchange, UserDetails userDetails,String rawPassword)
{
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(userDetails.getUsername(),rawPassword);
return reactiveAuthenticationManager.authenticate(token).filter(auth -> auth.isAuthenticated()).flatMap(auth ->
{
SecurityContextImpl securityContext = new SecurityContextImpl();
securityContext.setAuthentication(auth);
return securityContextRepository.save(exchange,securityContext).then(Mono.just(auth));
});
}

how to prevent the user repeat-login

In my application,I do not want two user login with the same login name.
For example, user1 login with name "test1",then user2 try to login with "test1" too,but at this moment the user1's formauthentication does not expire,so the login of user2 should be denied.
I created a cache class to record all the active session:
public class SessionDb {
private static Dictionary<string, HttpSessionState> sessionDB=new Dictionary<string, HttpSessionState>();
public SessionDb() {
}
public static void addUserAndSession(string name, HttpSessionState session) {
sessionDB.Add(name, session);
}
public static bool containUser(string name) {
//in fact,here I also want to check if this session is active or not ,but I do not find the method like session.isActive() or session.HasExpire() or something else.
return sessionDB.ContainsKey(name);
}
public static void removeUser(string name) {
if(sessionDB.ContainsKey(name)) {
sessionDB.Remove(name);
}
}
}
In the login.aspx.cs:
//check the name and password
if(checkNameAndPass(sUserName, sUserPwd)) {
if(!SessionDb.containUser(sUserName)) {
//let the user login
Session["current_user_name"] = sUserName;
SessionDb.addUserAndSession(sUserName, Session);
FormsAuthentication.RedirectFromLoginPage(UserName.Text, false);
}
else {
//
this.error.Text=string.Format("user {0} have logined!", sUserName);
}
}
Global.asax:
void Session_End(object sender, EventArgs e)
{
SessionDb.removeUser(Session["current_user_name"].ToString());
}
But it seems that it the Session_End() method is called at some time according the timeout setting in the sessionState.
Obviously I need the the SessionDb remove the related session when the authentication timeout.
Any idea to improve my code? or any other idea to implement my requirement?
I just do not want the user repeat-login(with the same name).
UPDATE:
BTW,I think my code also have some problems: I store the log in token using the Session,but how about if the formauthentication have timeout but the session does not?
If you are using a Membership provider:
A user is considered online if the current date and time minus the UserIsOnlineTimeWindow property value is earlier than the LastActivityDate for the user.
from MSDN Article
so you can simple use the check
Membership.IsOnline();
before you login the user.
In asp.net site how to prevent multiple logins of same user id?
Another approach (Disclaimer: I have not tested this.):
In the web.config add userIsOnlineTimeWindow to 1 and in the loggingIn event handler:
protected void Login1_LoggingIn(object sender, LoginCancelEventArgs e)
{
MembershipUser u = Membership.GetUser(Login1.UserName);
Response.Write(u.IsOnline);
if (u.IsOnline)
{
Login1.FailureText = "A user with this username is already logged in.";
e.Cancel = true;
}

Resources