#spring login

185 messages ยท Page 1 of 1 (latest)

heady pier
#

a

zealous harborBOT
#

โŒ› This post has been reserved for your question.

Hey @heady pier! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

heady pier
#

@half forum hello

#

and this is the filter chain bean

half forum
heady pier
#

yeah, i added it because this is when i'm using the UserDetailsService

half forum
#

Do you want to use the UserDetailsService?

heady pier
#

if it works, sure

half forum
#

Do you maybe have another UserDetailService?

#

Can you show the full stack trace (ideally as text, not as an image)?

heady pier
#

i have this one

heady pier
heady pier
# heady pier

i'm just unable to log in using these credentials here

half forum
heady pier
#

that's when i use this

half forum
#

in your PasswordEncoder bean, try replacing it with PasswordEncoderFactories.createDelegatingPasswordEncoder()

heady pier
#

okay

heady pier
half forum
#

Do you have any AuthenticationProvider?

half forum
heady pier
heady pier
#

i don't really know anything about AuthenticationProviders

#

so i'll stick to UserDetailsService for now i guess

half forum
#

A custom UserDetailService could look like this:

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Override
    public UserDetails loadUserByUsername(String username) {
        UserDetails userDetails = getUserDetailsFromUsername(username);
        if(userDetails == null){
            throw new UsernameNotFoundException("User not found: " + username);
        }
        return userDetails;
    }
}
heady pier
#

what's @Transactional

half forum
#

you can create the UserDetails object like this:

org.springframework.security.core.userdetails.User
  .withUsername(user.getPhoneNumber())
  .password(user.getPassword())
  .authorities(yourGrantedAuthorities)
  .build();
half forum
heady pier
#

mine looks about the same except no german and no @Transactional

half forum
#

Didn't plan to include Transactional

heady pier
#

oh

#
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserRepository repo;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = this.repo.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException(username);
        }
        return new CustomUserDetails(user);
    }


}
#

this is mine

half forum
#

Can you show your CustomUserDetails class?

heady pier
half forum
#

yeah the getPassword() should return the encoded (hashed) password

#

with your PasswordEncoder

heady pier
#

where do i get the password encoder from

half forum
#

Just don't store plain text passwords

#

like when registering the user, you should encode the password and then never use the plain text password again

heady pier
#

server side?

half forum
#

yes

heady pier
#

where would i save a test user

#

where i create the bean?

#

where is registration even done

half forum
heady pier
#
@Bean
    public UserDetailsService userDetailsService() {
        this.repo.save(new User("user", "", passwordEncoder().encode("password")));
        return new UserDetailsServiceImpl();
    }
``` like this?
half forum
#
@Controller
public class RegisterController{
  private UserRepository userRepo;
  private PasswordEncoder passwordEncoder;
  public RegisterController(UserRepository userRepo, PasswordEncoder passwordEncoder){
    this.userRepo=userRepo;
    this.passwordEncoder=passwordEncoder;
  }
  @PostMapping("/register")
  public String register(@RequestParam("username")String username, @RequestParam("password") String password)
    //additional logic
    userRepo.save(new User(username, passwordEncoder.encode(passwod)));
    return "redirect:/login";
}
#

I wrote that in Discord so idk whether this is correct lol

#

you could do something like that for registering

heady pier
#

is the PasswordEncoder injected

heady pier
zealous harborBOT
# heady pier okay thanks

If you are finished with your post, please close it.
If you are not, please ignore this message.
Note that you will not be able to send further messages here after this post have been closed but you will be able to create new posts.

half forum
#

and in your UserDetailService, you could do something like

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserRepository repo;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return this.repo.findByUsername(username)
          .map(CustomUserDetails::new)
          .orElseThrow(()->new UsernameNotFoundException(username));
    }
}
#

since the UserRepository already stores encoded passwords, it should work

#

but you shouldn't have any plaintext passwords in your DB

heady pier
#

okay

#

i see

#

findByUsername isn't an optional

#

i'll make it one i guess

half forum
#

if it returns null, you could also do a null check

#

it doesn't matter

heady pier
#

gonna eat first ๐Ÿ‘๐Ÿป

heady pier
half forum
#

or let them stay on the register site and tell them to use a nonexisting username

heady pier
#

hmm

#

could i like add a parameter to the url and make thymeleaf show a message if that parameter is present

half forum
#

yes

#

e.g. you could redirect to /whatever?someParam

#

and check that in thymeleaf

heady pier
#

since it's a rest controller

#

do i return a 302

half forum
#

return new ResponseEntity<>(response, HttpStatus.FOUND);

#

If you really have a RestController and not a Controller

heady pier
#

i do

half forum
#

but you don't have to use a redirect

heady pier
half forum
#

the content

#

oh right you need an additional Location header

heady pier
#

yeah

half forum
#

you could use a MultiValueMap

#

but I'd like the second answer there more:

HttpHeaders headers = new HttpHeaders();
headers.setLocation(URI.create(newUrl));
return new ResponseEntity<>(headers, HttpStatus.MOVED_PERMANENTLY);
#

hm?

#

lol

heady pier
#

for the url, do i use localhost

half forum
#

also, there's that interesting comment

heady pier
#

oooo you can do .status

#

that's cool

half forum
#

if you want 302, use HttpStatus.FOUND ofc

heady pier
#

gonna test this

#

huh

#

i think it doesn't use the UserDetailsService

half forum
heady pier
#

it should print the user right, or at least null

half forum
#

If so, try removing it

heady pier
#

just this

half forum
#

what's that supposed to be?

#

oh I see

heady pier
#

the bean

heady pier
half forum
#

Is that bean created?

heady pier
#

wdym

half forum
#

Can you show the full class of that?

#

Also, when sharing code, please share it as text in a codeblock

#

if possible

half forum
heady pier
# half forum Can you show the full class of that?
package xyz.mirai666.uwupaste.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import xyz.mirai666.uwupaste.UserRepository;
import xyz.mirai666.uwupaste.model.CustomUserDetails;
import xyz.mirai666.uwupaste.model.User;

import java.util.Optional;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserRepository repo;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return Optional.ofNullable(this.repo.findByUsername(username))
                .map(e -> {System.out.println(e); return e;})
                .map(CustomUserDetails::new)
                .orElseThrow(() -> new UsernameNotFoundException(username));
    }


}
half forum
#

actually, that shouldn't matter

#

Can you also share your main class?

heady pier
heady pier
# half forum Can you also share your main class?
package xyz.mirai666.uwupaste;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class UwUPasteApplication {

    public static void main(String[] args) {
        SpringApplication.run(UwUPasteApplication.class, args);
    }

}
half forum
#

If you have @Service, it should automatically create the bean without an explicit @Bean method

heady pier
#

ah

#

is it a problem if it's creating it twice maybe

half forum
#

maybe

#

And your UserRepository is a JPA repository?

heady pier
half forum
#

ig User is annotated with @Entity?

heady pier
#

yes

half forum
#

Check whether UserDetailsServiceImpl#loadUserByUsername is executed

#

not the .map(e -> {System.out.println(e); return e;})

heady pier
half forum
#

Add a System.out.println before the Optional.ofNullable(this.repo.findByUsername(username))

heady pier
#

hmm it worked this time

#

both things got printed

#

i guess the problem was that the bean got created twice

half forum
#

Does it work?

heady pier
#

the login does

half forum
#

nice

heady pier
#

thank you :D

zealous harborBOT
# heady pier thank you :D

If you are finished with your post, please close it.
If you are not, please ignore this message.
Note that you will not be able to send further messages here after this post have been closed but you will be able to create new posts.

half forum
#

So what doesn't work?

heady pier
#

the registering

#

i'll try to make that work

half forum
#

good luck

heady pier
#

thanks

heady pier
half forum
#

assuming you want it to work without logging in first

heady pier
#

what the fuck did i do wrong

heady pier
half forum
half forum
#

no annoying users

#

only the admin

heady pier
#

yeah

half forum
#

and friends of the admin maybe

heady pier
#

i hate users fr fr

heady pier
zealous harborBOT
# heady pier thank you

If you are finished with your post, please close it.
If you are not, please ignore this message.
Note that you will not be able to send further messages here after this post have been closed but you will be able to create new posts.

half forum
heady pier
#

truly

heady pier
#

shit is being sent like this ๐Ÿ’€

#

no json

heady pier
#

ah got it i think i can change it

half forum
#

text/plain?

heady pier
half forum
#

I mean, you can just use @RequestParam for reading these things

heady pier
#

i used @RequestBody

half forum
#
@PostMapping("/register")
public WHATEVER register(@RequestParam("username") String username, @RequestParam("password") String password, @RequestParam("email") String email){
  //TODO
}
heady pier
#

ah

heady pier
#

sob

zealous harborBOT
# heady pier thanks

If you are finished with your post, please close it.
If you are not, please ignore this message.
Note that you will not be able to send further messages here after this post have been closed but you will be able to create new posts.

heady pier
#

/login?usernameExists get redirected to /login

heady pier
#

how do i get the currently logged in user

half forum
#

SecurityContextHolder.getContext()

#

or you add an Authentication parameter