I am new to groovy and spring boot.I start to work on login with spring boot.
I need to pass two additional parameters to the CustomAuthToken class.
I can pass only one.When I assign other variable to some value auth fail.
This is my code.
CustomAuthFilter.groovy
Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
if (!request.post) {
throw new AuthenticationServiceException("not supported: $request.method")
}
String username = (obtainUsername(request) ?: '').trim()
String password = (obtainPassword(request) ?: '').trim()
String extrafield1 = request.getParameter("extrafield1")
String extrafield2 = request.getParameter("extrafield2")
def authentication = new CustomAuthToken(username, password, extrafield1, null, false, false, false)
HttpSession session = request.getSession(false)
if (session || getAllowSessionCreation()) {
request.session['SPRING_SECURITY_LAST_USERNAME_KEY'] = TextEscapeUtils.escapeEntities(username)
}
return getAuthenticationManager().authenticate(authentication)
}
CustomAuthToken.groovy
CustomAuthToken(Object principal, Object credentials, String extrafield1, String PVM, Boolean isAccept, Boolean isLogEnabled, Boolean is3PLEnabled) {
super(principal, credentials)
extra1 = extrafield1
}
It is working and I can access the extra1 field.
But when I try to pass anther parameter it's not working.
CustomAuthToken(Object principal, Object credentials, String extrafield1, String extrafield2, String PVM, Boolean isAccept, Boolean isLogEnabled, Boolean is3PLEnabled) {
super(principal, credentials)
extra1 = extrafield1
extra2 = extrafield2
}
When I try this extra2 is passing. But auth is fail.
Can anyone have an idea about this?
My guess is that
CustomAuthToken extends UsernamePasswordAuthenticationToken
If that's the case, you need to change the super constructor call from
super(principal, credentials)
to
super(principal, credentials, Collections.emptyList())
You see, the constructor you are invoking sets authenticated=false
public UsernamePasswordAuthenticationToken(Object principal, Object credentials) {
super(null);
this.principal = principal;
this.credentials = credentials;
setAuthenticated(false);
}
So you want to invoke the correct constructor
public UsernamePasswordAuthenticationToken(Object principal, Object credentials,
Collection<? extends GrantedAuthority> authorities) {
super(authorities);
this.principal = principal;
this.credentials = credentials;
super.setAuthenticated(true); // must use super, as we override
}
Related
I have an application which was working with (email/password) login process.
Now i have implemented LDAP auth.
A user enter in the authenticate process, if the database doesn't know him, it comes in the ldap process, and if it works, then we create his account in the database.
Next we receive the JWT token.
The problem is that if we retry to connect, new UsernamePasswordAuthenticationToken(email, password); is returning authenticated false. But credentials are OK, it should works...
I don't understand what is happening.. user is shown in the database with the password encrypted..
#Service
#RequiredArgsConstructor
public class OpenLdapAuthenticationProvider implements AuthenticationProvider {
#Value("${spring.ldap.enabled}")
private Boolean enableLDAP;
#Autowired
private LdapTemplate ldapTemplate;
private final UserService userService;
#Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String email = authentication.getName();
String password = authentication.getCredentials().toString();
// This method returns authenticated false !
Authentication authenticationWithDatabase = this.tryAuthWithDatabase(email, password);
if (authenticationWithDatabase.isAuthenticated() == false) {
if (enableLDAP == true) {
boolean authenticationWithLdap = this.tryAuthWithLdap(email, password);
if (authenticationWithLdap == true) {
UserDataDTO userDataDTO = this.retrieveUserInformationFromLDAP(email);
userDataDTO.setEmail(email);
userDataDTO.setPassword(password);
List<AppUserRole> userRoles = new ArrayList<>();
userRoles.add(AppUserRole.ROLE_DEV_VIEW);
userDataDTO.setAppUserRoles(userRoles);
boolean trySignup = userService.signup(userDataDTO);
if (trySignup == true) {
return this.tryAuthWithDatabase(email, password);
} else {
throw new InternalServerErrorException("Your account is not in database. Sign in with LDAP was OK, but registration failed. This should not happen.");
}
} else {
throw new UnAuthorizedErrorException(
"The connection has been refused (by the database and ldap). Check your credentials.");
}
} else {
throw new UnAuthorizedErrorException(
"The connection has been refused by the database and cannot be made by ldap because it has been disabled.");
}
} else {
return authenticationWithDatabase;
}
}
private Authentication tryAuthWithDatabase(String email, String password) {
return new UsernamePasswordAuthenticationToken(email, password);
}
private boolean tryAuthWithLdap(String email, String password) {
Filter filter = new EqualsFilter("mail", email); // mail = le champs dans l'arbre LDAP
return ldapTemplate.authenticate(LdapUtils.emptyLdapName(), filter.encode(), password);
}
public UserDataDTO retrieveUserInformationFromLDAP(String email) {
LdapQuery query = LdapQueryBuilder.query().where("objectClass").is("user").and("mail").is(email);
return ldapTemplate.search(query,
(AttributesMapper<UserDataDTO>) attributes ->
UserDataDTO.builder()
.name(attributes.get("givenName").get().toString())
.surname(attributes.get("sn").get().toString())
.username(attributes.get("displayName").get().toString())
.team(attributes.get("department").get().toString())
.build()).get(0);
}
#Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
}
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
#RequiredArgsConstructor
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
private JwtTokenProvider jwtTokenProvider;
#Autowired
private OpenLdapAuthenticationProvider openLdapAuthenticationProvider;
public WebSecurityConfig(JwtTokenProvider jwtTokenProvider) {
this.jwtTokenProvider = jwtTokenProvider;
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(this.openLdapAuthenticationProvider);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterBefore(corsFilter(), ChannelProcessingFilter.class);
http.csrf().disable();
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.authorizeRequests()
.antMatchers("/api/v3/authentificate").permitAll()
.antMatchers("/api/v3/signup").permitAll()
.anyRequest().authenticated();
http.apply(new JwtTokenFilterConfigurer(jwtTokenProvider));
}
#Override
public void configure(WebSecurity web) throws Exception {
// Allow swagger to be accessed without authentication
web.ignoring().antMatchers("/v3/api-docs/**")//
.antMatchers("/swagger-resources/**")//
.antMatchers("/swagger-ui/**")
.antMatchers("/swagger-ui.html");
}
#Override
#Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
#Configuration
public class GenericBeanConfig {
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(12);
}
#Bean
public ModelMapper modelMapper() {
return new ModelMapper();
}
}
Thanks for any help, i really don't understand what's happening..
If you check UsernamePasswordAuthenticationToken.class, you will see 2 constructors:
/**
* This constructor can be safely used by any code that wishes to create a
* <code>UsernamePasswordAuthenticationToken</code>, as the {#link #isAuthenticated()}
* will return <code>false</code>.
*
*/
public UsernamePasswordAuthenticationToken(Object principal, Object credentials) {
super(null);
this.principal = principal;
this.credentials = credentials;
setAuthenticated(false);
}
/**
* This constructor should only be used by <code>AuthenticationManager</code> or
* <code>AuthenticationProvider</code> implementations that are satisfied with
* producing a trusted (i.e. {#link #isAuthenticated()} = <code>true</code>)
* authentication token.
* #param principal
* #param credentials
* #param authorities
*/
public UsernamePasswordAuthenticationToken(Object principal, Object credentials,
Collection<? extends GrantedAuthority> authorities) {
super(authorities);
this.principal = principal;
this.credentials = credentials;
super.setAuthenticated(true); // must use super, as we override
}
The same can be seen in its documentation
Spring security's default implementation expects you to provide at least one granted authority to your user instance
That happens because Authentication provider receives an Authentication object not authenticated as input only username and password, by applying its logic (fetching from database, etc) if the result matches it returns an Authentication object username, password and its authorities if it doesnt match it returns that same input object
To solve your problem, you can try the following purely illustrative code:
// omitted code above
private Authentication tryAuthWithDatabase(String email, String password) {
// call your database or repository or service
// var fetchData receives the object from database
// perform token the matching against the fetch data
if( resultMatches ) {
return new UsernamePasswordAuthenticationToken(email, password, fetchData.getAuthorities() );
}
else {
return new UsernamePasswordAuthenticationToken( email, password );
}
}
// omitted code bellow
I hope i´ve helped. Let me know if you made it. Cheers!
Hello so i have this method in JwtUtill
public Boolean validateToken(String token, UserDetails userDetails) {
final String username = extractEmail(token);
return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
}
But how can i request UserDetails in controller?
#GetMapping("/validateToken")
public String validateToken(#RequestHeader(value="token") String token) {
if(jwtUtil.validateToken(token,???)) {
}
}
Angular side
public isTokenExpired(): Observable<string> {
const headers = new HttpHeaders().set('token', localStorage.getItem('token'));
return this.httpClient.get<string>('http://localhost:8080/api/validateToken', {headers, responseType: 'text' as 'json'});
}
Also as frontend im using angular
You can simply inject it using #AuthenticationPrincipal. Eg:
#GetMapping("/validateToken")
public String validateToken(#AuthenticationPrincipal UserDetails userDetails, ...
It seems like you are using jwt, you don't need UserDetails to compare it with.
change methods as :
public Boolean validateToken(String token) {
final String username = extractEmail(token);
return (!StringUtils.isEmpty(username) && !isTokenExpired(token));
}
#GetMapping("/validateToken")
public String validateToken(#RequestHeader(value="token") String token) {
if(jwtUtil.validateToken(token)) {
}
}
If your token is invalid you will not get exception in extractEmail method and if it is expired then method isTokenExpired will return false.
UserDetails comes in the security context in the principal
UserDetails userDetails =
(UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
I'm trying to implement Abstract Auditable Entity in my current Microservice architecture. It is working fine for a single module but I'm confused on how to pass the SecurityContext across multiple modules.
I've already tried by transferring the token as a header from my zuul-service (auth-server) to other core modules and the value is always null.
Also, I tried passing the SecurityContext using feign client but it didn't work for me either.
Cannot get JWT Token from Zuul Header in Spring Boot Microservice Module
Audit Logging in Spring Microservices
Session Management in microservices
public class JwtTokenAuthenticationFilter extends OncePerRequestFilter {
private final JwtConfig jwtConfig;
public JwtTokenAuthenticationFilter(JwtConfig jwtConfig) {
this.jwtConfig = jwtConfig;
}
private static final int FILTER_ORDER = 0;
private static final boolean SHOULD_FILTER = true;
private static final Logger logger = LoggerFactory.getLogger(AuthenticationFilter.class);
#Override
protected void doFilterInternal(HttpServletRequest request1, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
RequestContext ctx = RequestContext.getCurrentContext();
HttpServletRequest request = ctx.getRequest();
String header = request1.getHeader(jwtConfig.getHeader());
if (header == null || !header.startsWith(jwtConfig.getPrefix())) {
chain.doFilter(request1, response);
return;
}
/* new token getting code*/
String token = header.replace(jwtConfig.getPrefix(), "");
try {
Claims claims = Jwts.parser()
.setSigningKey(jwtConfig.getSecret().getBytes())
.parseClaimsJws(token)
.getBody();
String username = claims.getSubject();
System.out.println(username);
if (username != null) {
#SuppressWarnings("unchecked")
List<String> authorities = (List<String>) claims.get("authorities");
UsernamePasswordAuthenticationToken auth =
new UsernamePasswordAuthenticationToken(
username,
null, authorities.stream().map(
SimpleGrantedAuthority::new
).collect(Collectors.toList()));
SecurityContextHolder.getContext().setAuthentication(auth);
}
} catch (Exception e) {
SecurityContextHolder.clearContext();
}
System.out.println(String.format("%s request to %s", request1.getMethod(), request1.getRequestURL().toString()));
/* return null;*/
request1.setAttribute("header",token);
chain.doFilter(request1, response);
}
}
I have an spring mvc web application in which users login to session "session.setAttribute" classically. Whenever I need loggedin user data I use this data.
Now I want to add android app and what I want to learn do I have to add additional methods for each android request and send user data within it?
Or Is there away to make a request to same methods.
What is the consept for this kind of cloud apps? Do I have to write different methods for android requests? Because it is not possible session.getAttribute when wemake an android request, it returns null.
User user = userService.getByUserNameAndPassword(userName, password);
if (user != null) {
if (user.isActive()) {
Account account = new Account(user, request.getRemoteAddr());
HttpSession httpSession = request.getSession(true);
AccountRegistry.add(httpSession);
httpSession.setAttribute(Constant.ACCOUNT, account);
result.put(Constant.REF, Constant.SUCCESS);
}
public class Account {
private UserRightsHandler userRightsService = null;
private User user;
private String ipAddress;
private boolean admin;
public Account(User user, String ipAddress) {
this.user = user;
this.ipAddress = ipAddress;
userRightsService = new UserRightsHandler(user);
setAdmin(userRightsService.isAdmin());
}
public UserRightsHandler getUserRightsService() {
return userRightsService;
}
public User getUser() {
return this.user;
}
public String getIpAddress() {
return ipAddress;
}
public boolean isAdmin() {
return admin;
}
private void setAdmin(boolean admin) {
this.admin = admin;
}
}
public class AccountRegistry {
private static final Map<String, HttpSession> sessions = new HashMap<String, HttpSession>();
public static void add(HttpSession session) {
sessions.put(session.getId(), session);
}
public static void remove(HttpSession session) {
if (session != null) {
sessions.remove(session.getId());
session.setAttribute(Constant.ACCOUNT, null);
session.invalidate();
}
}
public static HttpSession getByHttpSessionID(String httpSessionID) {
Set<String> keys = sessions.keySet();
Iterator it = keys.iterator();
while (it.hasNext()) {
String sID = (String) it.next();
HttpSession session = sessions.get(sID);
if (sID.equals(httpSessionID)) {
return session;
}
}
return null;
}
public static void removeByHttpSessionID(String httpSessionID) {
HttpSession session = getByHttpSessionID(httpSessionID);
remove(session);
}
public static Account getCurrentAccount() {
HttpServletRequest request = ContextFilter.getCurrentInstance().getRequest();
HttpSession session = request.getSession();
return (Account) session.getAttribute(Constant.ACCOUNT);
}
}
#RequestMapping(value = "/changeStatus", method = RequestMethod.POST)
public #ResponseBody
String changeStatus(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
User editor = AccountRegistry.getCurrentAccount().getUser();
}
You can ask user send their user and password at the start of Android app via custom authenticate request like /appLogin then if it is correct creditentals you can return a key to user (to app) and store it to some variable during app run. Then when user want to do something send a request to server you can send it to a function with mapping like /appExampleService then you can check at that function this key and device valid depending on how you handle custom login process then this function call existing function that is used for web browsers that have mapping /exampleService. For example;
#JsonSerialize
#RequestMapping("/appExampleService")
public int someServiceForAppClient(
#RequestParam(value = "key", required = true) String apikey,
#RequestParam(value = "param", required = true) String someParam{
String name=userDAO.getUsernameFromApiKey(apikey);
return someService(someParam, name);
}
#JsonSerialize
#RequestMapping("/exampleService")
public int someServiceForWebClient(
#RequestParam(value = "param", required = true) String someParam) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String name = auth.getName();
return someService(someParam, name);
}
public int someService(String someParam,String name){
return doBusiness(someParam, name);
}
userDAO is just something I created for to get info of user with given key. And there is a service for App login as well which return that key to user when he started the app send his username and pass
So I have set up my shiro to have two Realms. A Username and Password Realm, using the standard UsernamePasswordToken. I have also set up a Custom Bearer Authentication Token that works off a token passed in from the user.
If i just use my passwordValidatorRealm it works find, if no user is found throws unknown account, if password doesn’t match throws incorrect credentials, perfect. But as soon as i put in my tokenValidatorRealm it throws a
org.apache.shiro.authc.AuthenticationException: Authentication token of type [class org.apache.shiro.authc.UsernamePasswordToken] could not be authenticated by any configured realms.
In this instance my tokenValidatorRealm returns null as no token was provided, so it moves on to the passwordValidatorRealm and just breaks.
Any ideas why introducing a second Realm will cause my working passwordValidatorRealm to break?
Have tried with different authentication strategies, and no luck there.
Using shiro 1.2.2
EDIT
I have two implementations, one for password and one for token
Password:
public class PasswordAuthorizingRealm extends AuthenticatingRealm {
#Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
if (authenticationToken instanceof UsernamePasswordToken) {
UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
String username = usernamePasswordToken.getUsername();
char[] password = usernamePasswordToken.getPassword();
if (username == null) {
throw new AccountException("Null usernames are not allowed by this realm!");
}
//Null password is invalid
if (password == null) {
throw new AccountException("Null passwords are not allowed by this realm!");
}
UserService userService = new UserServiceImpl();
User user = userService.getUserByUsername(username);
if (user == null) {
throw new UnknownAccountException("Could not authenticate with given credentials");
}
SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(username, user.getPassword(), "passwordValidatorRealm");
return simpleAuthenticationInfo;
} else {
return null;
}
}
}
and Bearer Token
public class TokenAuthorizingRealm extends AuthorizingRealm {
#Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
if (authenticationToken instanceof BearerAuthenticationToken) {
BearerAuthenticationToken bearerAuthenticationToken = (BearerAuthenticationToken) authenticationToken;
String username = "" + bearerAuthenticationToken.getPrincipal();
User user = userService.getUserByUsername(username);
//User with such username has not found
if (user == null) {
throw new UnknownAccountException("Could not authenticate with given credentials");
}
BearerAuthenticationInfo bearerAuthenticationInfo = new BearerAuthenticationInfo(user);
return bearerAuthenticationInfo;
}
}
Shiro config
[main]
hashService = org.apache.shiro.crypto.hash.DefaultHashService
hashService.hashIterations = 500000
hashService.hashAlgorithmName = SHA-256
hashService.generatePublicSalt = true
hashService.privateSalt = ****
passwordService = org.apache.shiro.authc.credential.DefaultPasswordService
passwordService.hashService = $hashService
passwordMatcher = org.apache.shiro.authc.credential.PasswordMatcher
passwordMatcher.passwordService = $passwordService
authc = my.BearerTokenAuthenticatingFilter
tokenValidatorRealm = my.TokenAuthorizingRealm
passwordValidatorRealm = my.PasswordAuthorizingRealm
passwordValidatorRealm.credentialsMatcher = $passwordMatcher
securityManager.realms = $tokenValidatorRealm,$passwordValidatorRealm
These have been stripped out a bit, removed logging and other unnecessary code
The BearerTokenAuthenticatingFilter, just basically checks if a token has been supplied in the header if has
private void loginUser(ServletRequest request, ServletResponse response) throws Exception {
BearerAuthenticationToken token = (BearerAuthenticationToken) createToken(request, response);
if (token == null) {
String msg = "createToken method implementation returned null. A valid non-null AuthenticationToken "
+ "must be created in order to execute a login attempt.";
throw new IllegalStateException(msg);
}
try {
Subject subject = getSubject(request, response);
subject.login(token);
onLoginSuccess(token, subject, request, response);
} catch (AuthenticationException e) {
HttpServletResponse httpResponse = WebUtils.toHttp(response);
httpResponse.sendRedirect("login");
}
}
BearerAuthenticationInfo class
public class BearerAuthenticationInfo implements AuthenticationInfo {
private final PrincipalCollection principalCollection;
private final User user;
public BearerAuthenticationInfo(User user) {
this.user = user;
this.principalCollection = buildPrincipalCollection(user);
}
public PrincipalCollection getPrincipals() {
return principalCollection;
}
public Object getCredentials() {
return user.getUsername();
}
private PrincipalCollection buildPrincipalCollection(User user) {
Collection<String> principals = new ArrayList<String>();
principals.add(user.getUsername());
return new SimplePrincipalCollection(principals, "tokenValidatorRealm");
}
}
Looks like it is expected behavior.
If you look at the javadoc for ModularRealmAuthenticator:
* #throws AuthenticationException if the user could not be authenticated or the user is denied authentication
* for the given principal and credentials.
*/
protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
If you are having problems with the exception, you might need to change the code that calls the authentication to expect this exception.
Left for other searches:
You might have a missing supports method in your TokenAuthorizingRealm class.
Something like
#Override
public boolean supports(AuthenticationToken token) {
return token instanceof BearerAuthenticationToken;
}
should be present.
This discussion help me solve a similar problem. I wanted to authenticate a user by the application itself, not using any Shiro default implementation. To do that we must subclass AuthenticatingRealm, override doGetAuthenticationInfo and declare this realm as the validation one.
public class PasswordAuthorizingRealm extends AuthenticatingRealm {
#Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
In Shiro.ini:
passwordValidatorRealm = my.PasswordAuthorizingRealm