The spring boot login process has this error: org.springframework.security.authentication.BadCredentialsException: Bad credentials", - spring-boot

I am trying to implement a login functionality, from the stored user credentials.
but it gives error as :
org.springframework.security.authentication.BadCredentialsException: Bad credentials",
note:
Password is stored encrypted in database.
Controller code:
#PostMapping("/login")
public ResponseEntity<Map<String, Object>> login(#RequestBody JwtRequest authenticationRequest) throws Exception {
String encodedPassword = this.passwordEncoder.encode( authenticationRequest.getPassword());
String userName = authenticationRequest.getUsername();
try {
authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
userName,
encodedPassword
)
);
}catch(Exception e){
throw new CustomErrorException(
HttpStatus.INTERNAL_SERVER_ERROR,
"the authentication process has errors : "+e.toString()
);
}
final Employee emp = employeeService.findOne(authenticationRequest.getUsername());
if(emp != null){
System.out.println(" *** the employee ******** "+emp.toString());
}else{
System.out.println(" *** the employee not found ******** ");
}
final CustomeEmployee cEmp = customeEmployeeService.loadUserByUsername(authenticationRequest.getUsername());
final String token = jwtTokenUtil.generateToken(cEmp);
System.out.println("the request cam e along wy step 2");
/** -------------------------- */
ArrayNode authorities = mapper.createArrayNode();
for(GrantedAuthority authority : cEmp.getAuthorities()) {
authorities.add(authority.getAuthority());
}
Map<String, Object> result = getConfiguration(emp, cEmp);
result.put("token", token);
return ResponseEntity.ok(result);
}
Appearantly the process is not passing throug the
authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
userName,
encodedPassword
)
);
It says the credential errors.
Note: Password and username is 100% correct.

Related

Map LDAP groups to OAuth2 UserDetails in Spring Boot web app

After failed attempts to get CAS Single Sign Out working, we decided to try out OAuth2 using OpenID Connect with our Spring Boot web apps. Now we only need OAuth for SSO and to provide authentication - we're not storing username/password in a db or anything. We are using Google LDAP to grant authorities. I cannot find any solid example of using Google LDAP for authorities with OAuth2. My OAuth2 code is pretty simple so far. Here's my WebSecurityConfig so far:
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests(authorizeRequests -> authorizeRequests
.mvcMatchers("/home").permitAll()
.anyRequest().authenticated())
.oauth2Login(oauthLogin -> oauthLogin.permitAll());
}
and one of my endpoints that works:
#GetMapping("/user/me")
public String userDetails(#AuthenticationPrincipal OAuth2User user) {
Map<String, Object> attributes = user.getAttributes();
String username = (String) attributes.get("email");
return username;
}
Now here is what I used with my CAS and LDAP config. This block of code would pull all LDAP groups and map them to roles using SimpleGrantedAuthority. I've tried a ton of different configs, but nothing has worked.
private LdapContext getLdapReadContext(){
LdapContext ctx = null;
try{
Hashtable<String,String> env = new Hashtable<>();
env.put(Context.INITIAL_CONTEXT_FACTORY,ldapCtxFactory);
env.put(Context.SECURITY_AUTHENTICATION,"Simple");
env.put(Context.SECURITY_PRINCIPAL,ldapUsername);
env.put(Context.SECURITY_CREDENTIALS,ldapPassword);
env.put(Context.PROVIDER_URL,ldapURL);
ctx = new InitialLdapContext(env,null);
}catch(NamingException e){
e.printStackTrace();
}
return ctx;
}
public List<String> Groups(LdapContext ctx, AttributePrincipal principal){
String uid = "uid";
List<String> groups = new LinkedList<>();
NamingEnumeration answer = null;
if(principal!=null){
Map attributes =principal.getAttributes();
if(attributes.get(uid)!=null){
uid=attributes.get(uid).toString();
try{
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
String searchFilter = "(&(objectClass=groupOfNames)(member=uid="+uid+","+ldapBase+"))";
String[] attrIDs = {"cn"};
constraints.setReturningAttributes(attrIDs);
answer = ctx.search(ldapGroupBase,searchFilter,constraints);
while (answer.hasMore()){
Attributes attrs = ((SearchResult)answer.next()).getAttributes();
groups.add(attrs.get("cn").toString());
}
}catch(Exception ignored){
}finally{
if (answer !=null){
try{
answer.close();
}catch(Exception ignored){
}
}
if (ctx != null){
try{
ctx.close();
}catch(Exception ignored){
}
}
}
}
}
if (groups.isEmpty()){
groups.add("STUDENT");
}
return groups;
}
#Override
public UserDetails loadUserDetails (#Autowired Authentication authentication) throws UsernameNotFoundException {
CasAssertionAuthenticationToken casAssertionAuthenticationToken = (CasAssertionAuthenticationToken) authentication;
AttributePrincipal principal = casAssertionAuthenticationToken.getAssertion().getPrincipal();
Map attributes = principal.getAttributes();
String user = (String)attributes.get("username");
String email = (String)attributes.get("email");
String fname = (String)attributes.get("fname");
String lname = (String)attributes.get("lname");
String VNumber = (String)attributes.get("UDC_IDENTIFIER");
String uid = (String)attributes.get("uid");
String role = "user";
String username = authentication.getName();
List<String> grouplist = null;
grouplist = Groups(getLdapReadContext(), principal);
Collection<SimpleGrantedAuthority> collection = new ArrayList<SimpleGrantedAuthority>();
for (int i =0; i<grouplist.size(); i++) {
collection.add(new SimpleGrantedAuthority((grouplist.get(i)).substring(4)));
}
return new User(username, "",collection);
}

Generate Access token and Refresh token without username and password

I am implementing oauth2 with spring-security using springboot2.
I am authenticating user using spring-security only and returning a user Object back by using username and password. (http://localhost:8181/login)
Here users might be multiple with same mail. so again from user object which i got i am taking userid and sending to (http://localhost:8181/oauth/token)
here i want to pass only grant_type and userId not username and password again in order to generate access token and refresh token using oauth2.
How can i acheive this.
can i get username and password from previous request. And how i can configure in oauth2 to fulfill my requirement.
please help.
In below code i am authenticating one user by keeping limit 1 later i am fetching all users with same mail id. password is same for all.
#Override
#Transactional
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
User user = new User();
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
.getRequest();
String stringuserId = request.getParameter("userId");
Long userId = 0L;
try {
if (stringuserId != null) {
userId = Long.parseLong(stringuserId);
System.out.println(userId);
System.out.println(request.getParameter("username"));
user = userRepository.findByUserId(userId).orElseThrow(
() -> new UsernameNotFoundException("User Not Found with -> username or email : " + email));
System.out.println(user.toString());
return UserPrinciple.build(user);
} else {
Set<GrantedAuthority> authorities = new HashSet<>();
CustomUser userDetails = new CustomUser(email, "", authorities);
String checkUser = "SELECT \"USER_ID\",\"EMAIL_ID\",\"PASSWORD\" FROM \"TU_IOT_PLATFORM_PROD\".\"USER_MASTER\" WHERE \"EMAIL_ID\"='john#test.com' LIMIT 1;";
List<Map<String, Object>> toValues = new ArrayList<Map<String, Object>>();
toValues = jdbcTemplate.queryForList(checkUser);
if(toValues.size()>0) {
for (Map<String, Object> map : toValues) {
userDetails.setUserId((int) map.get("USER_ID"));
userDetails.setEmail((String)map.get("EMAIL_ID"));
userDetails.setPassword((String)map.get("PASSWORD"));
}
}else {
throw new UsernameNotFoundException("User Not Found with -> username or email : " + email);
}
System.out.println(userDetails.toString());
return userDetails;
}
} catch (NumberFormatException e) {
userId = 0L;
user = userRepository.findByEmail(email).orElseThrow(
() -> new UsernameNotFoundException("User Not Found with -> username or email : " + email));
}
return UserPrinciple.build(user);
}
}
var tokenExpiration = Startup.TokenExpiration; //超期时长
var data = new Dictionary<string, string>
{
{"as:client_id", clientId },
{"userID",user.Id},
{"commID","0" }
};
var IssueTime = DateTime.UtcNow;
var properties = new AuthenticationProperties(data)
{
IssuedUtc = IssueTime,
ExpiresUtc = IssueTime.Add(tokenExpiration),
};
var oAuthIdentity = _userManager.CreateIdentity(user, "JWT");
var ticket = new AuthenticationTicket(oAuthIdentity, properties);
var accessToken = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket);
//var accessToken = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);
//var rToken= Startup.OAuthOptions.RefreshTokenFormat.Protect(ticket);
var context = new AuthenticationTokenCreateContext(Request.GetOwinContext(), Startup.OAuthOptions.AccessTokenFormat, ticket);
//await Startup.OAuthOptions.AccessTokenProvider.CreateAsync(context);
//accessToken = context.Token;
var refreshTkLifeTime = ;
context.OwinContext.Set("as:clientAllowedOrigin", "*");
context.OwinContext.Set("as:clientRefreshTokenLifeTime", refreshTkLifeTime.ToString());
await Startup.OAuthOptions.RefreshTokenProvider.CreateAsync(context);
var refreshToken = context.Token;
return new JObject(
new JProperty("access_token", accessToken),
new JProperty("refresh_token", refreshToken),
new JProperty("token_type", "bearer"),
new JProperty("expires_in", tokenExpiration.TotalSeconds.ToString()),
new JProperty(".issued", IssueTime.ToString()),
new JProperty(".expires", IssueTime.Add(tokenExpiration).ToString())
);

Authorization code malformed or invalid when getting Azure AD access token with Spring

I have this error when I try to generate the token.
I have do this tutorial http://blog.xebia.in/index.php/2017/12/21/spring-security-and-oauth2-with-azure-active-directory/.
My problem is when I try to get an access token after I have the code.
I have this error:
Here is the related code:
public AuthenticationResult getAccessToken(AuthorizationCode authorizationCode, String currentUri) throws Throwable {
String authCode = authorizationCode.getValue();
ClientCredential credential = new ClientCredential(clientId, clientSecret);
AuthenticationContext context = null;
AuthenticationResult result = null;
ExecutorService service = null;
try {
service = Executors.newFixedThreadPool(1);
context = new AuthenticationContext(authority + tenant + "/", true, service);
//here are the error
Future<AuthenticationResult> future = context.acquireTokenByAuthorizationCode(authCode, new URI(currentUri), credential, resource, null);
result = future.get();
} catch (ExecutionException e) {
throw e.getCause();
} finally {
service.shutdown();
}

spring authentication for rest api to include hardcoded and lookup

I have a rest API application that authenticates requests by verifying credentials with a database lookup. I need to now add an additional feature that will allow a specific set of credentials to be allowed that is not a record in the database table. Basically I need to hardcode these credentials; but what I found is that the spring authenticationprovider for userDetails does not authenticate this and I am not sure why or how. I added an if statement just before retrieving the dataset result to validate the user credentials but it still does not work.Here is my code:
#SuppressWarnings("deprecation")
#Override
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException
{
Logger logger = LoggerFactory.getLogger("com.reader.AuthService.loadUserByUsername");
logger.info("Request--");
UserDetails userDt = null;
logger.info("USER:" + username);
Connection con = null;
String query = "SELECT * FROM Customers WHERE username= ?";
logger.info("Making SQL request");
try
{
con= dataSource.getConnection();
String password = null;
String authority = null;
int enabled = 0;
try(Connection dbConn = dataSource.getConnection();
PreparedStatement pst = dbConn.prepareStatement(query);)
{
pst.setString(1, username);
ResultSet rs = pst.executeQuery();
if(username.equalsIgnoreCase("sampleUser")){
username = "sampleUser";
password="1234567_sample";
List ls = new ArrayList();
ls.add(new GrantedAuthorityImpl("ROLE_USER"));
userDt = new User(username, password, enabled==1?true:false , true, true, true, ls);
return userDt;
}
if (rs.next())
{
username = rs.getString("username");
password = rs.getString("password");
authority = "ROLE_USER";
enabled = rs.getInt("isactive");
List ls = new ArrayList();
ls.add(new GrantedAuthorityImpl(authority));
userDt = new User(username, password, enabled==1?true:false , true, true, true, ls);
}
else
{
System.out.println("No credentials present in DB for username" + username);
throw new UsernameNotFoundException(
"Bad Credentials", username);
}
}
catch(SQLException e)
{
System.out.println("API: "+e.getMessage());
e.printStackTrace();
}
con.close();
}
catch(UsernameNotFoundException e)
{
throw e;
}
catch(Exception e1)
{
e1.printStackTrace();
}
return userDt;
In the server-context file I declare the user ref service to this class file above:
<beans:bean id="authservice"
class="com.reader.security.AuthService" />
<security:authentication-manager>
<security:authentication-provider
user-service-ref="authservice" />
</security:authentication-manager>
I think the problem starts here in AbstractUserDetailsAuthenticationProvider:
try {
preAuthenticationChecks.check(user);
additionalAuthenticationChecks(user, (UsernamePasswordAuthenticationToken) authentication);
} catch (AuthenticationException exception) {
if (cacheWasUsed) {
// There was a problem, so try again after checking
// we're using latest data (i.e. not from the cache)
cacheWasUsed = false;
user = retrieveUser(username, (UsernamePasswordAuthenticationToken) authentication);
preAuthenticationChecks.check(user);
additionalAuthenticationChecks(user, (UsernamePasswordAuthenticationToken) authentication);
} else {
throw exception;
}
}
here is the exception:
org.springframework.security.authentication.DisabledException: User is disabled
could someone please assist or at least explain how this authentication works.
EDIT:
console response:
10:29:04.703 [http-nio-8080-exec-2]
DEBUG o.s.s.w.a.w.BasicAuthenticationFilter - Basic
Authentication Authorization header found for user
'internalUser'
10:29:04.705 [http-nio-8080-exec-2]
DEBUG o.s.s.authentication.ProviderManager - Authentication attempt
using org.springframework.security.authentication.dao.
DaoAuthenticationProvider
10:29:04.707 [http-nio-8080-exec-2] INFO
c.b.f.AuthService.loadUserByUsername - Request--
10:29:04.707 [http-nio-8080-exec-2] INFO
c.b.f.AuthService.loadUserByUsername - USER:internalUser
10:29:04.707 [http-nio-8080-exec-2] INFO
c.b.f.AuthService.loadUserByUsername - Making SQL request
AbandonedObjectPool is
used (org.apache.commons.dbcp.AbandonedObjectPool#3517a554)
LogAbandoned: false
RemoveAbandoned: true
RemoveAbandonedTimeout: 300
10:32:51.434 [http-nio-8080-exec-2]
DEBUG o.s.s.a.d.DaoAuthenticationProvider - User account is disabled
10:37:12.083 [http-nio-8080-exec-2]
DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached
instance of singleton
bean 'userAuthenticationErrorHandler'
10:37:12.083 [http-nio-8080-exec-2]
DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance
of singleton bean 'org.springframework.context.annotation.
internalScheduledAnnotationProcessor'
It's because your code is setting enabled as false as you initialized enabled integer to zero and later below enabled==1?true:false which will always return false. So i think you missed to set enabled = 1 in case of your "sampleUser" inside if statement
int enabled = 0;
if(username.equalsIgnoreCase("sampleUser")){
username = "sampleUser";
password="1234567_sample";
List ls = new ArrayList();
ls.add(new GrantedAuthorityImpl("ROLE_USER"));
userDt = new User(username, password, enabled==1?true:false , true, true, true, ls);
return userDt;
}
loadUserByUsername(String username) gets called when authentication is completed
for authentication purpose you need to override authenticate() and use it as given below
#Component
public class CustomAuthenticationProvider implements AuthenticationProvider{
#Autowired
private CustomUserService userService;
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String username = authentication.getName();
String password = (String) authentication.getCredentials();
CustomUser user = userService.loadUserByUsername(username);
if (user == null || !user.getUsername().equalsIgnoreCase(username)) {
throw new BadCredentialsException("Username not found.");
}
if (!password.equals(user.getPassword())) {
throw new BadCredentialsException("Wrong password.");
}
Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
return new UsernamePasswordAuthenticationToken(user, password, authorities);
}
public boolean supports(Class<?> arg0) {
return true;
}
}
and declare it in security xml
<authentication-manager>
<authentication-provider ref="customAuthenticationProvider"/>
</authentication-manager>

session.getAttribute returns null

I'am using jsp and servlet to realize the authentication before any access to the application
The is the code of my doPost method:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
Account account;
try {
//Checking if the user already exists
account = accountBesinessLocal.findByLogin(String.valueOf(username));
if (account != null) {
logger.log(Level.WARNING, "[User exists:{0}]", username);
if (accountBesinessLocal.authentificateUser(String.valueOf(username), String.valueOf(password))) {
HttpSession session = request.getSession(true);
System.out.println(session);
session.setAttribute("username", account.getLogin());
session.setAttribute("password", account.getPassword());
System.out.println("this "+session.getAttribute(username)+" is connected");
response.sendRedirect(home.xhtml");
} else {
request.setAttribute("erreur", "Incorrect Authentication");
getServletContext().getRequestDispatcher("/loginForm.jsp").forward(request, response);
}
} else {
request.setAttribute("erreur", "Incorrect Authentication");
logger.log(Level.WARNING, "[User does not exist:{0}]", username);
getServletContext().getRequestDispatcher("/loginForm.jsp").forward(request, response);
}
} finally {
}
}
When i try to get the login of the user conneced with session.getAttribute(username);
it returns null.
How can i solve this?
You must use
session.getAttribute("username")
and not
session.getAttribute(username)
the value of username is whatever the user has entered in the login input field. It's not "userame".
Side note: your code doesn't compile, s you might be running code that isn't the one ou posted.

Resources