@panic08

Как установить кастомный метод в principial?

Помогите пожалуйста, в общем у меня такая проблема. Я весь интернет перекопал, но не смог найти нужную информацию. В моем приложении после авторизации пользователю нужно вывести его количество денег, при каждой регистрации в базе данных у всех должен быть столбец money. Все это я сделал, но у меня возникла проблема. В index.html после авторизации выводится сообщение Welcome
Welcome <span sec:authentication="principal.username"> User</span>

То есть Welcome <имя авторизованного пользователя>.
Но теперь мне нужно выводить его количество денег
Your money
Your money <span sec:authentication="principal.getMoney()"> Tenge</span>

Но к сожалению это не работает, я пробовал в loadUserByUsername возвращать
return new org.springframework.security.core.userdetails.User (user.getEmail(),  user.getMoney(), user.getPassword(), mapRolesToAuthorities(user.getRoles()));

Но у меня выводится ошибка
Cannot resolve constructor 'User(String, int, String, Collection)'
Пробовал в маппинге ставить Principial principial, не помогает.
Мой код:
SecurityConfig:
package net.javaguides.springboot.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import net.javaguides.springboot.service.UserService;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

	@Autowired
	private UserService userService;
	
	@Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
	
	@Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider auth = new DaoAuthenticationProvider();
        auth.setUserDetailsService(userService);
        auth.setPasswordEncoder(passwordEncoder());
        return auth;
    }
	
	@Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authenticationProvider());
    }
	
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests().antMatchers(
				 "/registration**",
	                "/js/**",
	                "/css/**",
	                "/img/**").permitAll()
		.anyRequest().authenticated()
		.and()
		.formLogin()
		.loginPage("/login")
		.permitAll()
		.and()
		.logout()
		.invalidateHttpSession(true)
		.clearAuthentication(true)
		.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
		.logoutSuccessUrl("/login?logout")
		.permitAll();
	}
}

UserService:
package net.javaguides.springboot.service;
import net.javaguides.springboot.model.Role;
import net.javaguides.springboot.model.User;
import net.javaguides.springboot.repository.UserRepository;
import net.javaguides.springboot.web.dto.UserRegistrationDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collection;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService {
	private UserRepository userRepository;

	@Autowired
	private BCryptPasswordEncoder passwordEncoder;

	public UserServiceImpl(UserRepository userRepository) {
		super();
		this.userRepository = userRepository;
	}


	@Override
	public User save(UserRegistrationDto registrationDto) {
		User user=new User(registrationDto.getFirstName(),
							registrationDto.getLastName(), 
							registrationDto.getEmail(),
							 registrationDto.getMoney(),
							passwordEncoder.encode(registrationDto.getPassword()),
				(Collection<Role>) Arrays.asList(new Role("ROLE_USER")));
		
		return userRepository.save(user);
	}


	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
	{
		
		User user=userRepository.findByEmail(username);
		
		if(user==null)
		{
			throw new UsernameNotFoundException("Invalid Username or password");			
		}
		return new org.springframework.security.core.userdetails.User (user.getEmail(),  user.getMoney(), user.getPassword(), mapRolesToAuthorities(user.getRoles()));
	}





	private Collection<? extends GrantedAuthority> mapRolesToAuthorities(Collection<Role> roles){

		return roles.stream().map(role -> new SimpleGrantedAuthority(role.getName())).collect(Collectors.toList());
	
	}
}

UserRegistrationDTO:
package net.javaguides.springboot.web.dto;

public class UserRegistrationDto {

	private String firstName;
	private String lastName;
	private String email;
	private int money;
	private String password;

	
	public UserRegistrationDto(){}
	
	
	public UserRegistrationDto(String firstName, String lastName, String email, int money, String password) {
		super();
		this.firstName = firstName;
		this.lastName = lastName;
		this.email = email;
		this.money = money;
		this.password = password;
	}
	
	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public int getMoney() {
		return money;
	}

	public void setMoney(int money) {
		this.money = money;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}


}

MainController:
package net.javaguides.springboot.web;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.security.Principal;

@Controller
public class MainController {

	@GetMapping("/login")
	public String login() {
		return "login";
	}
	
	@GetMapping("/")
	public String home(Model model, Principal principal)
	{
		return "index";
	}
}

Помогите, пожалуйста. Я уже 3 дня не могу решить эту задачу
  • Вопрос задан
  • 101 просмотр
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы