为什么授权不起作用,而且无法访问页面?

huangapple go评论100阅读模式
英文:

Why authorization doesn't work and there is no access to the page?

问题

I'll provide a translation of the code and text you've provided without the code parts:

Link to my code. Through Postman, I make a request for user registration, it appears in the database, everything is fine, then in the special tab "Authorization" I enter in Postman, select 'Basic auth,' enter the data (user name and password), for example, the user name: petya@mail.ru and password: petya. Make a request to: 'http://localhost:8080/landlord/1'. You need to change the role from 'TENANT' to 'LANDLORD'. But I get an error in Postman, and nothing changes in the database. I understand that authorization does not work, maybe I wrote something wrong in the SecurityConfig file?

  1. <html lang="en">
  2. <head>
  3. <meta charset="utf-8">
  4. <title>Login Customer</title>
  5. </head>
  6. <body>
  7. <div class="container">
  8. <form class="form-signin" method="post" action="/auth/login">
  9. <h2 class="form-signin-heading">Login</h2>
  10. <p>
  11. <label for="username">Username</label>
  12. <input type="text" id="username" name="username" class="form-control" placeholder="Username" required>
  13. </p>
  14. <p>
  15. <label for="password">Password</label>
  16. <input type="password" id="password" name="password" class="form-control" placeholder="Password" required>
  17. </p>
  18. <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
  19. </form>
  20. </div>
  21. </body>
  22. </html>

SecurityConfig:

  1. @Configuration
  2. @EnableWebSecurity
  3. @EnableGlobalMethodSecurity(prePostEnabled = true)
  4. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  5. private final UserDetailsService userDetailsService;
  6. @Autowired
  7. public SecurityConfig(@Qualifier("userDetailsServiceImpl") UserDetailsService userDetailsService) {
  8. this.userDetailsService = userDetailsService;
  9. }
  10. @Override
  11. protected void configure(HttpSecurity http) throws Exception {
  12. http
  13. .csrf().disable()
  14. .authorizeRequests()
  15. .antMatchers("/").permitAll()
  16. .antMatchers("/user/registration").permitAll()
  17. .anyRequest()
  18. .authenticated()
  19. .and()
  20. .formLogin()
  21. .loginPage("/auth/login").permitAll()
  22. .defaultSuccessUrl("/auth/success")
  23. .and()
  24. .logout()
  25. .logoutRequestMatcher(new AntPathRequestMatcher("/auth/logout", "POST"))
  26. .invalidateHttpSession(true)
  27. .clearAuthentication(true)
  28. .deleteCookies("JSESSIONID")
  29. .logoutSuccessUrl("/auth/login");
  30. }
  31. @Override
  32. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  33. auth.authenticationProvider(daoAuthenticationProvider());
  34. }
  35. @Bean
  36. protected PasswordEncoder passwordEncoder() {
  37. return new BCryptPasswordEncoder(12);
  38. }
  39. @Bean
  40. protected DaoAuthenticationProvider daoAuthenticationProvider() {
  41. DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
  42. daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
  43. daoAuthenticationProvider.setUserDetailsService(userDetailsService);
  44. return daoAuthenticationProvider;
  45. }
  46. }

If you need further assistance or specific translations, please let me know.

英文:

Link my code. Through Postman, I make a request for user registration, it appears in the database, everything is fine, then in the special tab "Authorization" I enter in Postman, select Basic auth, enter the data (user name and password), for example, the user name : petya@mail.ru and password: petya Make a request to: http://localhost:8080/landlord/1 You need to change the role from TENANT to LANDLORD. But I get an error in Postman and nothing changes in the database. I understand that authorization does not work, maybe I wrote something wrong in the SecurityConfig file?

  1. &lt;html lang = &quot;en&quot;&gt;
  2. &lt;head&gt;
  3. &lt;meta charset = &quot;utf-8&quot;&gt;
  4. &lt;title&gt; Login Customer &lt;/title&gt;
  5. &lt;/head&gt;
  6. &lt;body&gt;
  7. &lt;div class = &quot;container&quot;&gt;
  8. &lt;form class = &quot;form-signin&quot; method = &quot;post&quot; action = &quot;/ auth / login&quot;&gt;
  9. &lt;h2 class = &quot;form-signin-heading&quot;&gt; Login &lt;/h2&gt;
  10. &lt;p&gt;
  11. &lt;label for = &quot;username&quot;&gt; Username &lt;/label&gt;
  12. &lt;input type = &quot;text&quot; id = &quot;username&quot; name = &quot;username&quot; class = &quot;form-control&quot; placeholder = &quot;Username&quot; required&gt;
  13. &lt;/p&gt;
  14. &lt;p&gt;
  15. &lt;label for = &quot;password&quot;&gt; Password &lt;/label&gt;
  16. &lt;input type = &quot;password&quot; id = &quot;password&quot; name = &quot;password&quot; class = &quot;form-control&quot; placeholder = &quot;Password&quot; required&gt;
  17. &lt;/p&gt;
  18. &lt;button class = &quot;btn btn-lg btn-primary btn-block&quot; type = &quot;submit&quot;&gt; Sign in &lt;/button&gt;
  19. &lt;/form&gt;
  20. &lt;/div&gt;
  21. &lt;/body&gt;
  22. &lt;/html&gt;

SecurityConfig

  1. @Configuration
  2. @EnableWebSecurity
  3. @EnableGlobalMethodSecurity(prePostEnabled = true)
  4. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  5. private final UserDetailsService userDetailsService;
  6. @Autowired
  7. public SecurityConfig(@Qualifier(&quot;userDetailsServiceImpl&quot;) UserDetailsService userDetailsService) {
  8. this.userDetailsService = userDetailsService;
  9. }
  10. @Override
  11. protected void configure(HttpSecurity http) throws Exception {
  12. http
  13. .csrf().disable()
  14. .authorizeRequests()
  15. /** На какие страницы человек имеет доступы */
  16. .antMatchers(&quot;/&quot;).permitAll()
  17. .antMatchers(&quot;/user/registration&quot;).permitAll()
  18. .anyRequest()
  19. .authenticated()
  20. .and()
  21. .formLogin()
  22. .loginPage(&quot;/auth/login&quot;).permitAll()
  23. .defaultSuccessUrl(&quot;/auth/success&quot;)
  24. .and()
  25. .logout()
  26. .logoutRequestMatcher(new AntPathRequestMatcher(&quot;/auth/logout&quot;, &quot;POST&quot;))
  27. .invalidateHttpSession(true)
  28. .clearAuthentication(true)
  29. .deleteCookies(&quot;JSESSIONID&quot;)
  30. .logoutSuccessUrl(&quot;/auth/login&quot;);
  31. }
  32. @Override
  33. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  34. auth.authenticationProvider(daoAuthenticationProvider());
  35. }
  36. @Bean
  37. protected PasswordEncoder passwordEncoder() {
  38. return new BCryptPasswordEncoder(12);
  39. }
  40. @Bean
  41. protected DaoAuthenticationProvider daoAuthenticationProvider() {
  42. DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
  43. daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
  44. daoAuthenticationProvider.setUserDetailsService(userDetailsService);
  45. return daoAuthenticationProvider;
  46. }
  47. }

答案1

得分: 0

Answer: 我没有这样的可能性,或者说它没有被实现,我不知道是否可能创建这样的东西。但我怀疑这是真实的。

首先,选择是否要创建带前端或不带前端的应用。如果不带前端,那么你只需要使用Rest控制器(我已经开始做了),并且可以从这个这个链接获取授权。接下来,在Postman中,使用请求体发起一个Post请求 - 这将是你的授权。注意务必阅读我附上的链接上的文章,它们会详细告诉你一切,我这里只有可能有问题的代码部分。还要阅读那里写的评论,特别是在英语网站上,有关获取“authenticationManager”的问题在那里有答案。我要提前说一下,它的方法必须在SecurityConfig类中注册。

希望我的答案能帮助某人并减轻他们的压力。

现在授权新方法的代码如下:

  1. @PostMapping("/login")
  2. public String getLoginPage(@RequestBody UserDto userDto) {
  3. userService.loginUser(userDto);
  4. return "login";
  5. }

你可以注意到我接受了UserDto,在其中包括:

  1. @NotNull
  2. @NotEmpty
  3. private String first_name;
  4. @NotNull
  5. @NotEmpty
  6. private String last_name;
  7. @NotNull
  8. @NotEmpty
  9. private String password;
  10. @NotNull
  11. @NotEmpty
  12. private String email;

这是授权检查的代码:

  1. public void loginUser(UserDto accountDto) {
  2. UsernamePasswordAuthenticationToken authReq
  3. = new UsernamePasswordAuthenticationToken(accountDto.getEmail(), accountDto.getPassword());
  4. Authentication auth = authenticationManager.authenticate(authReq);
  5. SecurityContext sc = SecurityContextHolder.getContext();
  6. sc.setAuthentication(auth);
  7. }
英文:

Answer: I don't have such a possibility, or rather it is not implemented, I don't know if it is possible to create such a thing or not. But I suspect it's real.

Initially, choose whether you want to create with or without a front, if without, then you only need Rest controllers(I started doing this) and you can get authorization from this and this links. Next, in Postman, make a Post request with the body - this will be your authorization. !ATTENTION! Be sure to read the articles on the links that I attached above, they tell you everything in detail, I do not have the full version of the code here, only the one that may have questions. Also read the comments that are written there, especially on the English-language site, there is an answer to the question about where to get the "authenticationManager". I say right away, its method must be registered in the SecurityConfig class.

I hope that my answer will help someone and save their nerves.

Code of what the new method for authorization looks like now:

  1. @PostMapping(&quot;/login&quot;)
  2. public String getLoginPage(@RequestBody UserDto userDto) {
  3. userService.loginUser(userDto);
  4. return &quot;login&quot;;
  5. }

You can notice that I accept UserDto, in it I have:

  1. @NotNull
  2. @NotEmpty
  3. private String first_name;
  4. @NotNull
  5. @NotEmpty
  6. private String last_name;
  7. @NotNull
  8. @NotEmpty
  9. private String password;
  10. @NotNull
  11. @NotEmpty
  12. private String email;

And here is the authorization check itself:

  1. public void loginUser(UserDto accountDto) {
  2. UsernamePasswordAuthenticationToken authReq
  3. = new UsernamePasswordAuthenticationToken(accountDto.getEmail(), accountDto.getPassword());
  4. Authentication auth = authenticationManager.authenticate(authReq);
  5. SecurityContext sc = SecurityContextHolder.getContext();
  6. sc.setAuthentication(auth);
  7. }

huangapple
  • 本文由 发表于 2020年8月11日 19:47:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/63357499.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定