How to get user id with Spring MVC? - java

I using the POST method for add Item to the database with Spring MVC. But each Item has field userId, it FOREIGN KEY to users table. Need to know user's id for this. I using Spring security for auth. May be there is a possibility get current user's id with ServletContext or HttpSession, may be spring security save user's id somewhere?
How to identify user which requested to the server with Spring MVC to data in the database?
#PostMapping("/get_all_items/add_item_page/add_item")
public String addItem(#RequestParam(value = "description")
final String description) {
final Item item = new Item();
item.setDescription(description);
item.setAuthorId(/* ??? */);
service.add(item);
return "redirect:get_all_items";
}
Spring security implementation with using UserDetails so all details hidden from me, and I don't know how to intervene in auth process and intercept user's id in the authorysation stage.
#Entity(name = "users")
public class User implements UserDetails {...}
#Autowired
private UserService userService;
#Autowired
private void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception {
auth.userDetailsService(userService);
}
Thank You!

Please try with this approach
Make sure that you have your own User pojo class
#Entity
public class MyUser {
#Id
private Long id;
private String username;
private String password;
private boolean isEnabled;
#ManyToMany
private List<MyAuthority> myAuthorities;
...
}
Also an Authority pojo in order to define the user roles
#Entity
public class MyAuthority {
#Id
private int id;
private String name; .....
Then the user repository, in this example I just declare a method to find by username and get an Optional to validate if the user exists.
public interface MyUserRepository extends CrudRepository<MyUser,Long> {
public Optional<MyUser> findFirstByUsername(String username);
}
Create a user class that extends from org.springframework.security.core.userdetails.User in order to wrap your custom user inside the definition of the spring security user.
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import java.util.Collection;
public class MySpringUser extends User {
private MyUser user;
public MySpringUser(MyUser myUser, Collection<? extends GrantedAuthority> authorities) {
super(myUser.getUsername(), myUser.getPassword(), myUser.isEnabled()
, true, true, true, authorities);
this.setUser(myUser);
}
public MyUser getUser() {
return user;
}
public void setUser(MyUser user) {
this.user = user;
}
}
And now the UserDetailService implementation, there is just one method to implement loadUserByUsername here is where the MyUserRepository is needed, in order to retrieve the user information from the repository by the username.
#Service
public class MyUserService implements UserDetailsService {
#Autowired
MyUserRepository myUserRepository;
#Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
Optional<MyUser> myUser = myUserRepository.findFirstByUsername(s);
return myUser.map( (user) -> {
return new MySpringUser(
user,
user.getMyAuthorities().stream().
map( authority ->
new SimpleGrantedAuthority(authority.getName())).
collect(Collectors.toList()));
}).orElseThrow(() -> new UsernameNotFoundException("user not found"));
}
}
And now you can inject the UserDetailService because its implementation will be injected form MyUserService class.
#Autowired
private UserService userService;
#Autowired
private void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception {
auth.userDetailsService(userService);
}
then with this approach you can inject the Principal object to your controller, and inside the method you can cast the Principal object to MySpringUser, it is because MySpringUser is extended from org.springframework.security.core.userdetails.User and User class implements the UserDetails interface. Of course you can get all the rest of custom fields of the user because its definition is wrapped inside the org.springframework.security.core.userdetails.User class
#PostMapping("/get_all_items/add_item_page/add_item")
public String addItem(#RequestParam(value = "description")
final String description, Principal principal) {
MySpringUser mySpringUser = (MySpringUser)principal;
final Item item = new Item();
item.setDescription(description);
item.setAuthorId(mySpringUser.getUser().getId());
service.add(item);
return "redirect:get_all_items";
}

I have tried many things but the best thing is to create custer User class which extend org.springframework.security.core.userdetails.User
package com.walterwhites.library.model.pojo;
import lombok.Getter;
import lombok.Setter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import java.util.Collection;
#Getter
#Setter
public class MyUser extends User {
long id;
public MyUser(long id, String username, String password, Collection<? extends GrantedAuthority> authorities) {
super(username, password, authorities);
this.id = id;
}
}
after you can use like below
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
UserDetails client = (UserDetails) auth.getPrincipal();
long id = ((MyUser) client).getId();
Cordially

UserDetails client = (UserDetails) auth.getPrincipal();
long id = ((User) client).getUserId();
System.out.println(id);
I got this error:
java.lang.ClassCastException: com.doc.importexport.implementation.UserPrincipal cannot be cast to com.doc.importexport.model.User

Related

There is no PasswordEncoder mapped for the id "null" with database authentication

I successfully build in-memory authentication. But when I going to build it with database comes this error.
There is no PasswordEncoder mapped for the id "null"
This is followed tutorial - Spring Boot Tutorial for Beginners, 10 - Advanced Authentication using Spring Security | Mighty Java
There are classes
SpringSecurityConfiguration.java
#Configuration
#EnableWebSecurity
public class SpringSecurityConfiguration extends
WebSecurityConfigurerAdapter{
#Autowired
private AuthenticationEntryPoint entryPoint;
#Autowired
private MyUserDetailsService userDetailsService;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated().and().httpBasic()
.authenticationEntryPoint(entryPoint);
}
}
AuthenticationEntryPoint.java
#Configuration
public class AuthenticationEntryPoint extends BasicAuthenticationEntryPoint{
#Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException, ServletException {
response.addHeader("WWW-Authenticate", "Basic realm -" +getRealmName());
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
PrintWriter writer = response.getWriter();
writer.println("Http Status 401 "+authException.getMessage());
}
#Override
public void afterPropertiesSet() throws Exception {
setRealmName("MightyJava");
super.afterPropertiesSet();
}
}
MyUserDetailsService .java
#Service
public class MyUserDetailsService implements UserDetailsService{
#Autowired
private UserRepository userRepository;
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByUsername(username);
if(user == null){
throw new UsernameNotFoundException("User Name "+username +"Not Found");
}
return new org.springframework.security.core.userdetails.User(user.getUserName(),user.getPassword(),getGrantedAuthorities(user));
}
private Collection<GrantedAuthority> getGrantedAuthorities(User user){
Collection<GrantedAuthority> grantedAuthority = new ArrayList<>();
if(user.getRole().getName().equals("admin")){
grantedAuthority.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
}
grantedAuthority.add(new SimpleGrantedAuthority("ROLE_USER"));
return grantedAuthority;
}
}
UserRepository interface
public interface UserRepository extends JpaRepository<User, Long>{
#Query("FROM User WHERE userName =:username")
User findByUsername(#Param("username") String username);
}
Role.java
#Entity
public class Role extends AbstractPersistable<Long>{
private String name;
#OneToMany(targetEntity = User.class , mappedBy = "role" , fetch = FetchType.LAZY ,cascade = CascadeType.ALL)
private Set<User> users;
//getter and setter
}
User.java
#Entity
public class User extends AbstractPersistable<Long>{
//AbstractPersistable class ignore primary key and column annotation(#Column)
private String userId;
private String userName;
private String password;
#ManyToOne
#JoinColumn(name = "role_id")
private Role role;
#OneToMany(targetEntity = Address.class, mappedBy = "user",fetch= FetchType.LAZY ,cascade =CascadeType.ALL)
private Set<Address> address; //Instead of Set(Unordered collection and not allow duplicates) we can use list(ordered and allow duplicate values) as well
//getter and setter}
If you have any idea plese inform. Thank you.
I changed MyUserDetailsService class adding passwordEncoder method.
Added lines
BCryptPasswordEncoder encoder = passwordEncoder();
Changed Line
//changed, user.getPassword() as encoder.encode(user.getPassword())
return new org.springframework.security.core.userdetails.User(--)
MyUserDetailsService.java
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
BCryptPasswordEncoder encoder = passwordEncoder();
User user = userRepository.findByUsername(username);
if(user == null){
throw new UsernameNotFoundException("User Name "+username +"Not Found");
}
return new org.springframework.security.core.userdetails.User(user.getUserName(),encoder.encode(user.getPassword()),getGrantedAuthorities(user));
}
#Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
As from Spring Security 5.x, Spring Security enforces you to use a password encoder if you're working with other than in-memory (production) databases.
Spring Security enforces this by activating the default DelegatingPasswordEncoder, which looks for PasswordEncoder beans.
By adding a BCryptPasswordEncoder, the DelegatingPasswordEncoder will return that instance to encrypt passwords.
#Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
I don't recommend you to do this, but if you really want to, you can override password encoding by adding {noop} to the password value.
This will treat the password by activating the NoOpPasswordEncoder instead of the default DelegatingPasswordEncoder and will treat your password as plain text.
Please note that this is not recommended if you deploy your app to a production environment!

What is the best practice to salt a password with spring security in spring boot?

I'm creating a REST API in java for an online store with Spring Boot, I want to securely store user passwords in the database,
for this I am using BCrypt that comes included with spring security, I use MySQL and JPA-Hibernate for persistence.
And I am implementing it as follows:
This is the user entity:
#Entity
#SelectBeforeUpdate
#DynamicUpdate
#Table (name = "USER")
public class User {
#Id
#GeneratedValue
#Column(name = "USER_ID")
private Long userId;
#Column(name = "ALIAS")
private String alias;
#Column(name = "NAME")
private String name;
#Column(name = "LAST_NAME")
private String lastName;
#Column(name = "TYPE")
private String type;
#Column(name = "PASSWORD")
private String password;
public String getPassword() {
return password;
}
/**
* When adding the password to the user class the setter asks if it is necessary or not to add the salt,
* if this is necessary the method uses the method BCrypt.hashpw (password, salt),
* if it is not necessary to add the salt the string That arrives is added intact
*/
public void setPassword(String password, boolean salt) {
if (salt) {
this.password = BCrypt.hashpw(password, BCrypt.gensalt());
} else {
this.password = password;
}
}
//Setters and Getters and etc.
}
This is the repository of the user class:
#Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
This is the service of the user class:
#Service
public class UserService{
private UserRepository userRepository;
#Autowired
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public User addEntity(User user) {
//Here we tell the password setter to generate the salt
user.setPassword(user.getPassword(), true);
return userRepository.save(user);
}
public User updateEntity(User user) {
User oldUser = userRepository.findOne(user.getUserId());
/*
*This step is necessary to maintain the same password since if we do not do this
*in the database a null is generated in the password field,
*this happens since the JSON that arrives from the client application does not
*contain the password field, This is because to carry out the modification of
*the password a different procedure has to be performed
*/
user.setPassword(oldUser.getPassword(), false);
return userRepository.save(user);
}
/**
* By means of this method I verify if the password provided by the client application
* is the same as the password that is stored in the database which is already saved with the salt,
* returning a true or false boolean depending on the case
*/
public boolean isPassword(Object password, Long id) {
User user = userRepository.findOne(id);
//To not create an entity that only has a field that says password, I perform this mapping operation
String stringPassword = (String)((Map)password).get("password");
//This method generates boolean
return BCrypt.checkpw(stringPassword, user.getPassword());
}
/**
*This method is used to update the password in the database
*/
public boolean updatePassword(Object passwords, Long id) {
User user = userRepository.findOne(id);
//Here it receive a JSON with two parameters old password and new password, which are transformed into strings
String oldPassword = (String)((Map)passwords).get("oldPassword");
String newPassword = (String)((Map)passwords).get("newPassword");
if (BCrypt.checkpw(oldPassword, user.getPassword())){
//If the old password is the same as the one currently stored in the database then the new password is updated
//in the database for this a new salt is generated
user.setPassword(newPassword, true);
//We use the update method, passing the selected user
updateEntity(user);
//We return a true boolean
return true;
}else {
//If the old password check fails then we return a false boolean
return false;
}
}
//CRUD basic methods omitted because it has no case for the question
}
This is the controller that exposes the API endpoints:
#RestController
#CrossOrigin
#RequestMapping("/api/users")
public class UserController implements{
UserService userService;
#Autowired
public UserController(UserService userService) {
this.userService = userService;
}
#RequestMapping( value = "", method = RequestMethod.POST )
public User addEntity(#RequestBody User user) {
return userService.addEntity(user);
}
#RequestMapping( value = "", method = RequestMethod.PUT )
public User updateEntity(#RequestBody User user) {
return userService.updateEntity(user);
}
#RequestMapping( value = "/{id}/checkPassword", method = RequestMethod.POST )
public boolean isPassword(#PathVariable(value="id") Long id, #RequestBody Object password) {
return userService.isPassword(password, id);
}
#RequestMapping( value = "/{id}/updatePassword", method = RequestMethod.POST )
public boolean updatePassword(#PathVariable(value="id") Long id, #RequestBody Object password) {
return userService.updatePassword(password, id);
}
}
This is where my question comes, my method is working but I feel it is not the best way, I do not feel comfortable changing the password setter I would prefer to keep the standard form of a setter, as in the user service I think there is Opportunity to handle the user and password update differently, so try to use the #DynamicUpdate annotation in the entity but it simply does not work properly since the fields not provided in the update instead of leaving them as they were are saved Like nulls.
What I'm looking for is a better way to handle the security of passwords using Spring Boot.
First of all you would like to have a unique field for each user in your online store (f.e. alias, or email), to use it as an identifier, without exposing id value to the end users.
Also, as I understand, you want to use Spring Security to secure your web application. Spring security uses ROLEs to indicate user authorities (f.e. ROLE_USER, ROLE_ADMIN). So it would be nice to have a field (a list, a separate UserRole entity) to keep track of user roles.
Let's assume, that you added unique constraint to User field alias (private String alias;) and added simple private String role; field. Now you want to set up Spring Security to keep '/shop' and all sub-resources (f.e. '/shop/search') open to everyone, unsecured, resource '/discounts' available only for registered users and resource '/admin' available for administrator only.
To implement it, you need to define several classes. Let's start with implementation of UserDetailsService (needed by Spring Security to get user information):
#Service
public class UserDetailsServiceImpl implements UserDetailsService {
private final UserRepository repository;
#Autowired
public UserDetailsServiceImpl(UserRepository repository) {
this.repository = repository;
}
#Override
public UserDetails loadUserByUsername(String alias) {
User user = repository.findByAlias(alias);
if (user == null) {
//Do something about it :) AFAIK this method must not return null in any case, so an un-/ checked exception might be a good option
throw new RuntimeException(String.format("User, identified by '%s', not found", alias));
}
return new org.springframework.security.core.userdetails.User(
user.getAlias(), user.getPassword(),
AuthorityUtils.createAuthorityList(user.getRole()));
}
}
Then, the main class for configuring Spring Security is one, that extends WebSecurityConfigurerAdapter (the example was taken from the application with a form based authentication, but you can adjust it for your needs):
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private UserDetailsService userDetailsService;
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/shop/**").permitAll()
.antMatchers("/discounts/**").hasRole("USER")
.antMatchers("/admin/**").hasRole("ADMIN")
.and()
.formLogin()
.usernameParameter("alias")
.passwordParameter("password")
.loginPage("/login").failureUrl("/login?error").defaultSuccessUrl("/")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.clearAuthentication(true)
.invalidateHttpSession(true)
.deleteCookies("JSESSIONID", "remember-me")
.logoutSuccessUrl("/")
.permitAll();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());
}
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
Then, in your UserService you can use something like:
...
#Autowired
private PasswordEncoder passwordEncoder;
public User addEntity(User user) {
...
user.setPassword(passwordEncoder.encode(user.getPassword()))
...
}
All other checks (f.e. for login attempt or for accessing resource) Spring Security will do automatically, according to the configuration. There are many more things to setup and consider, but I hope I was able to explain the overall idea.
EDIT
Define bean as follows within any spring Component or Configuration
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
Then autowire it in your UserService class
#Service
public class UserService {
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
#Autowired
public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
}
public User addEntity(User user) {
user.setPassword(passwordEncoder.encode(user.getPassword());
return userRepository.save(user);
}
...
public boolean isPassword(Object password, Long id) {
User user = userRepository.findOne(id);
String stringPassword = (String)((Map)password).get("password");
return passwordEncoder.matches(stringPassword, user.getPassword());
}
public boolean updatePassword(Object passwords, Long id) {
User user = userRepository.findOne(id);
String oldPassword = (String)((Map)passwords).get("oldPassword");
String newPassword = (String)((Map)passwords).get("newPassword");
if (!passwordEncoder.matches(oldPassword, newPassword)) {
return false;
}
user.setPassword(passwordEncoder.encode(newPassword));
updateEntity(user);
return true;
}
...
}
After that you can keep simple setter in User class.

SpringBoot JPA throws exception while making post request

Im making a small application where i can save user details using spring-boot. i created the entities and their corresponding repositories. When ever i make a post request to add a user the id of the user object which is null at the point of saving to the data base.This id is auto generated(Auto Increment) in MySQL. From the POST request i get 3 fields which are username,email,password. The User class contains fields id,username,email,password. I've added the annotations
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private Integer id;
for the id field. an the constructors are
public User() { }
public User(String username, String email, String password) {
this.username = username;
this.email = email;
this.password = password;
}
This is the error im getting.
The debugging process
my userService class
#Service
public class UserService implements UserServiceInterface {
#Autowired(required = true)
private UserRepository userrepository;
#Override
public User CreateNewUser(User user) {
return userrepository.save(user);
}
}
my userController class
#RestController
public class UserController {
UserService us = new UserService();
#RequestMapping(value ="/user",method = RequestMethod.POST)
public void RegisterUser(
#RequestParam(value="username") String username,
#RequestParam(value="email") String email,
#RequestParam(value="password") String password){
us.CreateNewUser(new User(username,email,password));
}
}
Any reason why i cant POST to save data to database? how to overcome this?
After digging through the code i found out the error. by creating a new instance of UserService us = new UserService(); this is not managed by Spring (Spring doesn't know about it and cannot inject UserRepository - this causes NullPointerException). there of instead of creting new instace it should extends the UserService class in this example.

Repository doesn't save data to H2 in-memory db

Here is my controller method:
// CREATE A USER
#PostMapping("/register")
public String createUser(
#RequestBody User user
) {
if (userService.userExists(user)) {
return "User already exists";
}
userService.saveUser(user);
return "Good job!";
}
UserServiceBean
#Service
public class UserServiceBean {
private UserRepository userRepository;
#Autowired
public UserServiceBean(UserRepository userRepository) {
this.userRepository = userRepository;
}
public User saveUser(User user) {
return userRepository.save(user);
}
public boolean userExists(User user) {
if (userRepository.findByUsername(user.getUsername()) == null) {
return false;
}
return true;
}
And my interface repository:
UserRepository
public interface UserRepository extends CrudRepository<User, Long> {
// TODO: 29.01.17 Create a query to find all todos for logged in user
#Query("select td from User u inner join u.toDoItems td where u = :user")
public Iterable<ToDoItem> findAllToDosForLoggedInUser(#Param("user") User user);
public User findByUsername(String username);
}
And here is my User Entity (getters and setters ommited)
#Entity
#Table (name = "USERS")
public class User extends BaseEntity {
#Column(name = "USERNAME")
private String username;
// TODO: 28.01.17 Find a way to store hashed and salted pws in DB
#Column(name = "PASSWORD")
private String password;
#Column(name = "EMAIL")
private String email;
// user can have many ToDoItems
#OneToMany(cascade = CascadeType.ALL, mappedBy = "user")
private Set<ToDoItem> toDoItems;
// JPA demands empty constructor
public User() {}
public User(String username, String password, String email) {
this.username = username;
this.password = password;
this.email = email;
}
When I shoot JSON at my localhost:8080/register:
{
"username":"ss",
"password":"mkyong.com",
"email":"asdasd#wp.pl"
}
I get response Good job! so it works fine. But when I check my DB at localhost:8080/console it just has Test Table and new User is not added.
I've got my hibernate ddl setup in application.properties set:
# Console to H2 database to check data
spring.h2.console.enabled=true
spring.h2.console.path=/console
spring.jpa.hibernate.ddl-auto=create-drop
So, how do I update my code that it creates table USERS and save created user into that db? I'm going to change my db later on, just using H2 to check if my controllers work fine but it shouldn't matter here.
EDIT:
Here is my RepositoryConfiguration.java:
#Configuration
#EnableAutoConfiguration
#EntityScan(basePackages = {"com.doublemc.domain"})
#EnableJpaRepositories(basePackages = {"com.doublemc.repositories"})
#EnableTransactionManagement
public class RepositoryConfiguration {
}
EDIT2:
When I want to register the same User again (using same JSON) then it gives me "User already exists" resposne so it is already in the db... Why can't I see it then? Maybe I've got H2 somewhere else? Not in the basic /console or different port? How can I check this?
I think you're missing the transactional part of your service. Did you define a transaction manager in your spring context ?
If so, you need to add the annotation #Transactional into your service. For example :
#Service
public class UserServiceBean {
#Transactional
public User saveUser(User user) {
return userRepository.save(user);
}
}
I had to add:
spring.datasource.url=jdbc:h2:~/test
spring.datasource.driver-class-name=org.h2.Driver
to application.properties and it works great now. I just thought I don't need it becasue Spring will auto-configure it for me but apparently it doesn't.

Authentication with Spring Security + Spring data + MongoDB

I want to use Spring security with MongoDB (using Spring data) and retrieve the users from my own database for spring security. However, I can not do that since my userservice type does not seem to be supported.
This is my UserService class:
public class UserService {
private ApplicationContext applicationContext;
private MongoOperations mongoOperations;
public UserService() {
applicationContext = new AnnotationConfigApplicationContext(MongoConfig.class);
mongoOperations = (MongoOperations) applicationContext.getBean("mongoTemplate");
}
public User find(String username) {
return mongoOperations.findOne(Query.query(Criteria.where("username").is(username)), User.class);
}
}
And my SecurityConfig class:
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
UserService userService;
#Autowired
public void configAuthBuilder(AuthenticationManagerBuilder builder) throws Exception {
builder.userDetailsService(userService); //THIS DOES NOT WORK
builder.inMemoryAuthentication().withUser("username").password("password").roles("USER");
}
}
The line I commented says:
The inferred type UserService is not a valid substitute for the bounded parameter <T extends UserDetailsService>.
How can I fix it so I can retrieve the users from my own database?
Service Layer
You have to create a separate service implementing org.springframework.security.core.userdetails.UserDetailsService and inject it inside the AuthenticationManagerBuilder.
#Component
public class SecUserDetailsService implements UserDetailsService{
#Autowired
private UserRepository userRepository;
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
/*Here add user data layer fetching from the MongoDB.
I have used userRepository*/
User user = userRepository.findByUsername(username);
if(user == null){
throw new UsernameNotFoundException(username);
}else{
UserDetails details = new SecUserDetails(user);
return details;
}
}
}
Model
UserDetails Should be also implemented. This is the POJO which will keep the user authenticated details by the Spring. You may include your Entity data object wrapped inside it, as I have done.
public class SecUserDetails implements UserDetails {
private User user;
public SecUserDetails(User user) {
this.user = user;
}
......
......
......
}
Security Config
Autowire the service that we created before and set it inside the AuthenticationManagerBuilder
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
SecUserDetailsService userDetailsService ;
#Autowired
public void configAuthBuilder(AuthenticationManagerBuilder builder) throws Exception {
builder.userDetailsService(userDetailsService);
}
}
Create your own authentication provider providing a class that extends the UserDetailservice.
Ensure content scanning is enable in your spring context xml file.
<authentication-provider user-service-ref="userModelService">
<password-encoder hash="sha" />
</authentication-provider>
#Service
public class UserModelService implements UserDetailsService
{
#Autowired
private UserModelRepositoryImpl repository;
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
{
UserModel user = repository.findByUsername(username);
if( user == null )
throw new UsernameNotFoundException( "Name not found!" );
List<SimpleGrantedAuthority> authorities = Arrays.asList(new SimpleGrantedAuthority( user.getRole()));
return new User(user.getUsername(), user.getSHA1Password(), authorities );
}
public void saveUserDetails(UserModel userModel)
{
repository.save(userModel);
}
}
This class will enable spring query mongo for the username and password required for authentication. Next create the user model class.
public class UserModel
{
private String id;
#Indexed(unique=true)
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
Create the user implementation class that extends the DAO.
#Service
public class UserModelService implements UserDetailsService
{
#Autowired
private UserModelRepositoryImpl repository;
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
{
UserModel user = repository.findByUsername(username);
if( user == null )
throw new UsernameNotFoundException( "Oops!" );
List<SimpleGrantedAuthority> authorities = Arrays.asList(new SimpleGrantedAuthority( user.getRole()));
return new User(user.getUsername(), user.getSHA1Password(), authorities );
}
Finally configure mongo and you're done.

Categories

Resources