I have two tables 'user' and 'role'.I want to create a login api (e.g '/login') which will take username and password as a json data. I want to check if given credential is a valid credential and if it is,then I want to set the user as authenticated user so that he/she may have the protected resources. I am new to spring boot framework and I don't know how to do so.I have read the offical documentation but cannot find any resources.Could someone help me on this?
You have number of choices to implement such authentication in Spring.
Case 1:- If you are building REST services then you can implement security in following ways:
i) - you can use Basic-Authentication to authenticate your user.
ii) - you can use OAuth2 to authenticate and authorize your user.
Case 2: If you are building web application
i) - you can use auth token (in case of Single page application SPA)
ii) - you can use session based authentication (traditional login form and all)
I Guess you are in beginner mode so i will recommend you to firstly understand the control flow user authentication in web app via login form. So Let's go through some code.
I'm assuming that you have set a basic spring project and now you are implementing security.
USER - Hibernate entity for your user table;
ROLE - Hibernate entity for your role table
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private CustomAuthProvider customAuthProvider;
#Override
protected void configure(HttpSecurity http) throws Exception {
// everyone is allowed tp view login page
http.authorizeRequests().antMatchers("/login").permitAll().and();
http.authorizeRequests().antMatchers("custom_base_path" + "**").authenticated().and().
formLogin().loginPage("/loginForm).loginProcessingUrl("/loginUser")
.usernameParameter("username").passwordParameter("password")
.defaultSuccessUrl("custom_base_path+ "home", true);
#Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(customAuthProvider);
}
//CustomAuthProvider
#Component
public class CustomAuthentiationProvider implements AuthenticationProvider{
#Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String userid = authentication.getName();
String password = authentication.getCredentials().toString();
Authentication auth = null;
try {
//write your custom logic to match username, password
boolean userExists = your_method_that_checks_username_and_password
if(userExists ){
List<Role> roleList= roleDao.getRoleList(userid);
if (roleList == null || roleList.isEmpty()) {
throw new NoRoleAssignedException("No roles is assigned to "+userid);
}
auth = new UsernamePasswordAuthenticationToken(userid, password,getGrantedAuthorities(roleList));
}
} catch (Exception e) {
log.error("error", e);
}
return auth;
}
#Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
public List<GrantedAuthority> getGrantedAuthorities(List<Role> roleList) {
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for (Role role : roleList) {
authorities.add(new SimpleGrantedAuthority(role.getRoleName());
}
return authorities;
}
}
NOTE: Please consider these codes to understand the logic of authentication. don't consider as perfect code(Not for production env.). You can ping me anytime i'll suggest you more about that.
Related
I want to rewrite my Vaadin application to Vaadin 21.
With the Vaadin starter builder (https://vaadin.com/start) I created a simple app.
Currently my main struggle is to apply my simple CustomAuthenticationProvider to the Security manager to able to use the #RolesAllowed({ "user", "admin","USER"}) annotation.
Main problem that my AuthToken is generated somewhere else...
Its generate somewhere an empty Granted Authrities and ignore my custom AuthProvider code.
Question:
How to nicely handle role based access control?
Where I can use this annotation correctly:
#RolesAllowed({ "user", "admin","USER"})
public class ProfileView extends VerticalLayout {
Console after login:
UsernamePasswordAuthenticationToken [Principal=c.farkas, Credentials=[PROTECTED], Authenticated=false, Details=WebAuthenticationDetails [RemoteIpAddress=0:0:0:0:0:0:0:1, SessionId=DDE103F559B2F64B917753636B800564], Granted Authorities=[]]
xxx[USERcica, admin, USER]
??UsernamePasswordAuthenticationToken [Principal=c.farkas, Credentials=[PROTECTED], Authenticated=true, Details=null, Granted Authorities=[USERcica, admin, USER]]
SecurityConfiguration.java
#EnableWebSecurity
#Configuration
public class SecurityConfiguration extends VaadinWebSecurityConfigurerAdapter {
#Autowired
private RequestUtil requestUtil;
#Autowired
private VaadinDefaultRequestCache vaadinDefaultRequestCache;
#Autowired
private ViewAccessChecker viewAccessChecker;
#Autowired
CustomAuthenticationProvider customAuthenticationProvider;
public static final String LOGOUT_URL = "/";
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
#Override
protected void configure(HttpSecurity http) throws Exception {
// super.configure(http);
http.csrf().ignoringRequestMatchers(requestUtil::isFrameworkInternalRequest);
// nor with endpoints
http.csrf().ignoringRequestMatchers(requestUtil::isEndpointRequest);
// Ensure automated requests to e.g. closing push channels, service
// workers,
// endpoints are not counted as valid targets to redirect user to on
// login
http.requestCache().requestCache(vaadinDefaultRequestCache);
ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry urlRegistry = http
.authorizeRequests();
// Vaadin internal requests must always be allowed to allow public Flow
// pages
// and/or login page implemented using Flow.
urlRegistry.requestMatchers(requestUtil::isFrameworkInternalRequest).permitAll();
// Public endpoints are OK to access
urlRegistry.requestMatchers(requestUtil::isAnonymousEndpoint).permitAll();
// Public routes are OK to access
urlRegistry.requestMatchers(requestUtil::isAnonymousRoute).permitAll();
urlRegistry.requestMatchers(getDefaultHttpSecurityPermitMatcher()).permitAll();
// all other requests require authentication
urlRegistry.anyRequest().authenticated();
// Enable view access control
viewAccessChecker.enable();
setLoginView(http, LoginView.class, LOGOUT_URL);
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// Custom authentication provider - Order 1
auth.authenticationProvider(customAuthenticationProvider);
// Built-in authentication provider - Order 2
/* auth.inMemoryAuthentication().withUser("admin").password("{noop}admin#password")
// {noop} makes sure that the password encoder doesn't do anything
.roles("ADMIN") // Role of the user
.and().withUser("user").password("{noop}user#password").credentialsExpired(true).accountExpired(true)
.accountLocked(true).roles("USER");*/
}
#Override
public void configure(WebSecurity web) throws Exception {
super.configure(web);
web.ignoring().antMatchers("/images/*.png");
}
}
CustomAuthenticationProvider.java
#Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
#Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String username = authentication.getName();
String password = authentication.getCredentials().toString();
System.out.println(authentication);
try {
// LdapContext ldapContext =
ActiveDirectory.getConnection(username, password);
List<GrantedAuthority> authorityList = new ArrayList<GrantedAuthority>();
authorityList.add(new SimpleGrantedAuthority("USER" + "cica"));
authorityList.add(new SimpleGrantedAuthority("admin"));
authorityList.add(new SimpleGrantedAuthority("USER"));
System.out.println("xxx"+authorityList.toString());
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
username, password, authorityList);
System.out.println("??" + usernamePasswordAuthenticationToken);
String id = VaadinSession.getCurrent() != null ? VaadinSession.getCurrent().getSession().getId() : "";
return usernamePasswordAuthenticationToken;
} catch (NamingException e) {
// e.printStackTrace();
// throw new CortexException("Authentication failed");
throw new BadCredentialsException("Authentication failed");
}
}
#Override
public boolean supports(Class<?> aClass) {
return aClass.equals(UsernamePasswordAuthenticationToken.class);
}
}
You must add the ROLE_ prefix to tell Spring Security that the GrantedAuthority is of type role.
authorityList.add(new SimpleGrantedAuthority("ROLE_USER" + "cica"));
authorityList.add(new SimpleGrantedAuthority("ROLE_admin"));
authorityList.add(new SimpleGrantedAuthority("ROLE_USER"));
I use LDAP authentication in my app.
I use this code:
#Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
String domain = customProperties.getAdDomain();
String url = customProperties.getAdUrl();
ActiveDirectoryLdapAuthenticationProvider provider = new ActiveDirectoryLdapAuthenticationProvider(domain,url);
provider.setConvertSubErrorCodesToExceptions(true);
provider.setUseAuthenticationRequestCredentials(true);
provider.setUserDetailsContextMapper(userDetailsContextMapper());
auth.authenticationProvider(provider);
auth.userDetailsService(new MyUserDetailsService());
}
Authentication takes place with an empty password. I know that I need to insert a check for an empty password, because Not all LDAP servers return an error in this case. How and where is it better to insert a check for a blank password?
Instead of using the ActiveDirectoryLdapAuthenticationProvider, you can make use of Spring's LdapTemplate to have a custom implementation of how you authenticate users against the LdapServer. You can refer to the recommendation here and here to configure the LDAP template.
Then, you can create a CustomAuthenticationProvider class to handle the authentication.
CustomAuthenticationProvider.class
public class CustomAuthenticationProvider implement AuthenticationProvider{
#Autowired
private LdapTemplate ldapTemplate;
#Override
public Authentication authenticate(Authentication auth) throws AuthenticationException{
String username = auth.getName;
String password = auth.getCredentials().toString();
.. Your code to check whether password is blank ..
AndFilter andFilter = new AndFilter();
andFilter.and(new EqualFilter("<LDAP USER ATTRIBUTE>",username))
.and(new EqualFilter("<LDAP GROUP ATTRIBUTE>","<USER GROUP>"));
boolean isValidUser = ldapTemplate.authenticate("",andFilter.encode(),password);
... Your code to complete the authentication ...
{
I prefer this approach as it gives me finer control on how to authenticate the user. Here is the link to the sample I implemented previously.
I am developing a web application that has the following requirements:
Allow the user to login
On the server side, the user is authenticated via a 3rd party REST web service.
The REST web service will return a unique token and key, if the authentication is successful.
Any subsequent requests to the REST web service must contain the token received in point 3 (above).
I am using spring-mvc and spring security for the web application.
So, I got a solution working, however I'm new to spring and not sure if the solution is correct.
Can someone please advise if:
Is the solution correctly implemented?
Does the solution impact performance in any way?
Does the solution create any security holes?
Thanks :)
Solution:
I created a MyUser object that will store the additional information received from the REST service.
public class MyUser implements Serializable {
private static final long serialVersionUID = 5047510412099091708L;
private String RestToken;
private String RestKey;
public String getRestToken() {
return RestToken;
}
public void setRestToken(String restToken) {
RestToken = restToken;
}
public String getRestKey() {
return RestKey;
}
public void setRestKey(String restKey) {
RestKey = restKey;
}
}
I then created a MyAuthenticationToken object that extends UsernamePasswordAuthenticationToken. This object will be used in the CustomAuthenticationProvider (point 3 below).
public class MyAuthenticationToken extends UsernamePasswordAuthenticationToken {
private static final long serialVersionUID = 7425814465946838862L;
private MyUser myUser;
public MyAuthenticationToken(Object principal, Object credentials, Collection<? extends GrantedAuthority> authorities, MyUser myUser){
super(principal, credentials, authorities);
this.myUser = myUser;
}
public MyUser getMyUser() {
return myUser;
}
public void setMyUser(MyUser myUser) {
this.myUser = myUser;
}
}
I created a custom authentication provider that will call the REST service for authentication and then store the additional information in the myUser and myAuthenticationToken objects.
public class CustomAuthenticationProvider implements AuthenticationProvider {
#Override
public Authentication authenticate (Authentication authentication) {
MyUser myUser = new MyUser();
MyAuthenticationToken authenticationToken = null;
String name = authentication.getName();
String password = authentication.getCredentials().toString();
//Just an example. This section will connect to a web service in order to authenticate the client
if (name.equals("justh") && password.equals("123456")) {
//Set the Token and Key Received from the REST WebService
myUser.setRestKey("RestKey");
myUser.setRestToken("RestToken");
List<GrantedAuthority> grantedAuths = new ArrayList<GrantedAuthority>();
grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
authenticationToken = new MyAuthenticationToken(name, password, grantedAuths, myUser);
return authenticationToken;
} else {
return null;
}
}
Finally, I can access the data stored in my controller
public ModelAndView adminPage(Authentication authentication) {
MyUser user = null;
//Get the additional data stored
if(authentication instanceof MyAuthenticationToken){
user = ((MyAuthenticationToken)authentication).getMyUser();
}
ModelAndView model = new ModelAndView();
model.addObject("title", "Spring Security Hello World");
model.addObject("message", "This is protected page - Admin Page!" + authentication.getName() + user.getRestKey() + user.getRestToken());
model.setViewName("admin");
return model;
}
Your approach is the right one. You should implement a custom AuthenticationManager and Authentication whenever your requirements exceeds a simple username password authentication flow.
But don't forget to comply with AuthenticationManager's interface contract.
I did something quite similar in my webmailer for authenticating against an smtp/imap server with javax.mail and it works flawlessly.
I need to programmatically login users that were authenticated through Facebook API. The reason for that is that there are number of items that are associated to each user (for example shopping cart), therefore once user is authenticated using Facebook API, I need to log the user in using spring security as well to be able to access his/her shopping cart.
Based on my research, there are many methods to implement it but I could not deploy any of them as I am sending log-in request from my code, also another problem is that some people created user object but they did not explain how to create it.
Those who created a user object but did not explain how.
From first example:this answer
Authentication auth =
new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
From second example: this one
34.User details = new User(username);
35.token.setDetails(details);
From third example: this one
Authentication authentication = new UsernamePasswordAuthenticationToken(user, null,
AuthorityUtils.createAuthorityList("ROLE_USER"));
Another example is here, it does not help because I need to log-in user from my own code not from browser; therefore I do not know how to populate HttpServletRequest object.
protected void automatedLogin(String username, String password, HttpServletRequest request) {
MyCode
...
if(isAuthenticatedByFB())
{
login(username);
return "success";
}
else{
return "failed";
}
Unfortunately it seems there is no "complete" support of programmatic login in Spring security. Here is how I've done it successfully:
#Autowired AuthenticationSuccessHandler successHandler;
#Autowired AuthenticationManager authenticationManager;
#Autowired AuthenticationFailureHandler failureHandler;
public void login(HttpServletRequest request, HttpServletResponse response, String username, String password) {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
token.setDetails(new WebAuthenticationDetails(request));//if request is needed during authentication
Authentication auth;
try {
auth = authenticationManager.authenticate(token);
} catch (AuthenticationException e) {
//if failureHandler exists
try {
failureHandler.onAuthenticationFailure(request, response, e);
} catch (IOException | ServletException se) {
//ignore
}
throw e;
}
SecurityContext securityContext = SecurityContextHolder.getContext();
securityContext.setAuthentication(auth);
successHandler.onAuthenticationSuccess(request, response, auth);//if successHandler exists
//if user has a http session you need to save context in session for subsequent requests
HttpSession session = request.getSession(true);
session.setAttribute("SPRING_SECURITY_CONTEXT", securityContext);
}
UPDATE Essentially the same is done by Spring's RememberMeAuthenticationFilter.doFilter()
This code is from Grails' Spring Security Core -Plugin, which is released under the Apache 2.0 license. I've added the imports just to point out what the types are exactly. The original author is Burt Beckwith.
import org.springframework.security.core.userdetails.UserCache;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
...
public static void reauthenticate(final String username, final String password) {
UserDetailsService userDetailsService = getBean("userDetailsService");
UserCache userCache = getBean("userCache");
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(
userDetails, password == null ? userDetails.getPassword() : password, userDetails.getAuthorities()));
userCache.removeUserFromCache(username);
}
The getBean-method merely provides the bean from application context.
I'm creating authentication service in Spring.
I'm using UserDetailsService to get form variables, but i found that loadUserByUsername has only one variable - userName.
How to get password ?
public class userAuthentication implements UserDetailsService{
private #Autowired
ASPWebServicesUtils aspWebServicesUtils;
#Override
public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
//how to get password ?
User user = new User("test", "test", true, true, true, true, getAuthorities(true));
return user;
}
private List<GrantedAuthority> getAuthorities(boolean isAdmin){
List<GrantedAuthority> authorityList = new ArrayList<GrantedAuthority>(2);
authorityList.add(new SimpleGrantedAuthority("USER_ROLE"));
if(isAdmin){
authorityList.add(new SimpleGrantedAuthority("ADMIN_ROLE"));
}
return authorityList;
}
//...
}
Thanks
If you look at the User object, the second parameter in the constructor is the password.
The UserDetailsService is used to load the user from a back-end structure like database. The loadUserByUsername method is called when a user tries to login with a username and password, then it is the responsibility of the service to load the user definition and return it to the security framework. The required details includes data like username, password, accountNonExpired, credentialsNonExpired, accountNonLocked and authorities.
Once the spring security receives the user object, it will validate the user against the password entered by the user and other data like user account status (accountNonExpired, credentialsNonExpired etc)
Some of the standard (out-of-the-box) mechanisms to retrieve the user information and provide authentication information are:
inMemoryAuthentication
jdbcAuthentication
ldapAuthentication
userDetailsService
If the above does not suit your purpose and you need to have a custom solution, you can create and configure a new authentication provider like so:
Security Configuration:
#Configuration
#EnableWebMvcSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
#Autowired
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(new CustomAuthenticationProvider());
}
....
}
Authentication Provider:
public class CustomAuthenticationProvider implements AuthenticationProvider {
#Override
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
String name = authentication.getName();
// You can get the password here
String password = authentication.getCredentials().toString();
// Your custom authentication logic here
if (name.equals("admin") && password.equals("pwd")) {
Authentication auth = new UsernamePasswordAuthenticationToken(name,
password);
return auth;
}
return null;
}
#Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
}
I believe a UserDetailsService is supposed to be used to acquire a UserDetails object from some back end storage, database, flat file, etc. Once you have that UserDetails, spring security (or you) have to compare it to the username (or other principals) and password (the credentials) provided by the user in order to authenticate that user.
I don't think you are using it the way it is intended.
Get password in UserDetailsService implementation by request.getParameter("password"):
public class MyUserDetailsService implements UserDetailsService {
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String password = request.getParameter("password"); // get from request parameter
......
}
}
RequestContextHolder is base on ThreadLocal.
If your project is base on Spring Framework (not Spring Boot), add RequestContextListener to web.xml
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
XML Implementation:
<authentication-manager alias="loginAuthenticationManager">
<authentication-provider ref="loginAuthenticationProvider" />
</authentication-manager>
<!-- Bean implementing AuthenticationProvider of Spring Security -->
<beans:bean id="loginAuthenticationProvider" class="com.config.LoginAuthenticationProvider">
</beans:bean>
AuthenticationProvider:
public class LoginAuthenticationProvider implements AuthenticationProvider {
#Override
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
String name = authentication.getName();
// You can get the password here
String password = authentication.getCredentials().toString();
// Your custom authentication logic here
if (name.equals("admin") && password.equals("pwd")) {
List<GrantedAuthority> grantedAuths = new ArrayList<>();
grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
return new UsernamePasswordAuthenticationToken(name, password, grantedAuths);
}
return null;
}
#Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
}
the loadUserByUsername(String name) is a method defined on an interface (userServicedetails I think), which your service implements. You have to write the implementation.
Just as you have to write the implementation for getPassword() or similar ... spring does not provide that. I imagine the password is stored in your user object, but you wrote that ... did you create a getPassword() method ?