Home > Blockchain >  Principal.getName() returns the email instead of username
Principal.getName() returns the email instead of username

Time:09-30

I've an application using Spring Security. I am trying to fetch the name of the user after the successful registation of the latter but when I am getting to the login page, I get the email instead of the name. I am providing a screenshot after the successful login.

Screenshot after login

In the above picture, I want the firstname, not the email address.

I am providing you the classes, I think that matter the most.

CONTROLLER CLASS

package com.andrekreou.iot.crypto.controller;

import com.andrekreou.iot.crypto.service.CryptoNewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;

@Controller
public class NewsHTMLController {

    CryptoNewsService cryptoNewsService;

    @Autowired
    public NewsHTMLController(CryptoNewsService cryptoNewsService) {
        this.cryptoNewsService = cryptoNewsService;
    }

    @GetMapping("/")
    public String main(Model model, Principal principal){
        String name = principal.getName();
        model.addAttribute("name",name);
        return "welcome";
    }

    @GetMapping("/login")
    public String getLoginView() {
        return "login";
    }
}

SECURITY CONFIGURATION CLASS

package com.andrekreou.iot.authentication.security;

import com.andrekreou.iot.authentication.user.ApplicationUserService;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@AllArgsConstructor
@EnableWebSecurity
public class ApplicationSecurityConfig {

    private final ApplicationUserService applicationUserService;

    private final BCryptPasswordEncoder bCryptPasswordEncoder;

    @Bean
    protected SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                    .antMatchers("/api/v*/registration/**","/register*","/login","/registration","/registration-complete").permitAll()
                    //.antMatchers("/show-news-contents").hasRole(ADMIN.name())
                    .anyRequest()
                    .authenticated()
                    .and()
                .formLogin()
                    .loginPage("/login")
                    .permitAll()
                    .defaultSuccessUrl("/",true)
                .and()
                .logout()
                    .logoutUrl("/logout")
                    .clearAuthentication(true)
                    .invalidateHttpSession(true)
                    .deleteCookies("JSESSIONID","Idea-2e8e7cee")
                    .logoutSuccessUrl("/login");

        return http.build();
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }

    @Bean
    public DaoAuthenticationProvider daoAuthenticationProvider() {
        DaoAuthenticationProvider provider =
                new DaoAuthenticationProvider();
        provider.setPasswordEncoder(bCryptPasswordEncoder);
        provider.setUserDetailsService(applicationUserService);
        return provider;
    }
}

LOGIN.HTML

<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>login</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet"
          integrity="sha384-/Y6pD6FV/Vv2HJnA6t vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
    <link href="https://getbootstrap.com/docs/4.0/examples/signin/signin.css" rel="stylesheet" crossorigin="anonymous">
    <style>
        body {
            background-color: #3e3e3e;
            color: white;
        }
        h2 {
            text-align: center;
        }
    </style>
</head>
<body>
<div >
    <form  method="post" action="/login">
        <h2 >Please Login</h2>
        <p>
            <label for="username" >Username</label>
            <input type="text" id="username" name="username"  placeholder="username" required=""
                   autofocus="">
        </p>
        <p>
            <label for="password" >Password</label>
            <input type="password" id="password" name="password"  placeholder="Password"
                   required="">
        </p>
        <button  type="submit">Login</button>
    </form>

    <form  method="get" action="/register">
        <button  type="submit">Register</button>
    </form>
</div>
</body>
</html>

APPLICATION USER CLASS

package com.andrekreou.iot.authentication.user;

import com.andrekreou.iot.authentication.security.ApplicationUserRole;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.persistence.*;
import java.util.Collection;
import java.util.Collections;

@Getter
@Setter
@EqualsAndHashCode
@NoArgsConstructor
@Entity
public class ApplicationUser implements UserDetails {

    @Id
    @SequenceGenerator(
            name = "user_sequence",
            sequenceName = "user_sequence",
            allocationSize = 1
            )
    @GeneratedValue(
            strategy = GenerationType.SEQUENCE,
            generator = "user_sequence"
    )
    private Long id;
    private String firstName;
    private String lastName;
    private String email;
    private String password;
    @Enumerated(EnumType.STRING)
    private ApplicationUserRole applicationUserRole;
    private  Boolean locked = false;
    private  Boolean enabled = false;


    //Constructor without the ID (it will be autogenerated)
    public ApplicationUser(String firstName,
                           String lastName,
                           String email,
                           String password,
                           ApplicationUserRole applicationUserRole) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
        this.password = password;
        this.applicationUserRole = applicationUserRole;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        SimpleGrantedAuthority authority =
                new SimpleGrantedAuthority(applicationUserRole.name());
        return Collections.singletonList(authority);
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return email;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return !locked;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return enabled;
    }
}

CodePudding user response:

Your code, at least what is posted, does not have a function getName(), perhaps you meant the getUserName(). But take another look at it.

@Override
    public String getUsername() {
        return email;
    }

You are getting exactly what you coded. Perhaps what need:

@Override
    public String getUsername() {
        return firstName || ' ' || lastName;1
    }

where || is concatenation. Sorry, but I do not specifically know the Spring Security function/operator for it.

  • Related