英文:
How to access a page with and without springboot authentication?
问题
以下是您提供的代码翻译:
首页面代码:
<body>
<div layout:fragment="content">
<h1>欢迎!</h1>
<form action="/search" method="POST">
<div class="form-group row">
<div class="col-sm-6" id="category_search">
<div class="dropdown">
<div class="input-group justify-content-center">
<div class="input-group-btn">
<button class="btn btn-md dropdown-toggle" type="button"
id="dropdownMenuButton" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false">选择一个类别</button>
<div class="dropdown-menu" onchange="selectMenu1"
aria-labelledby="dropdownMenuButton">
<a class="dropdown-item" href="#" data="Hotel">酒店</a> <a
class="dropdown-item" href="#" data="Food">快餐</a>
</div>
</div>
</div>
</div>
</div>
<div class="col-sm-3" id="search_city_id">
</div>
</div>
<div class="form-group row">
<div class="col-sm-3">
<input type="text" name="search" id="search"
class="form-control coloredInput" th:value="${search}" />
</div>
<button type="submit" class="btn btn-primary" value="search">搜索</button>
</div>
</form>
</div>
</body>
</html>
控制器类:
@Controller
public class RController {
@Autowired
private CustomUserDetailsService userService;
@RequestMapping("/home")
public String home(Model model) {
model.addAttribute("pointList", rRepository.findAll());
return "home";
}
@RequestMapping(value = "/search")
public ModelAndView search(Model model, @RequestParam("search") String search,
@RequestParam("search-entityType-value") String searchEntityTypeValue,
@RequestParam("selected_category") String selected_category) {
List<RAggrResults> result = RSearchRepository.searchRs(search, searchEntityTypeValue, selected_category);
LinkedHashMap<String, List<R>> hashMap = new LinkedHashMap<String, List<R>>();
for (int i = 0; i < result.size(); i++) {
List<R> rs_of_one_group = result.get(i).getRs();
hashMap.put(rs_of_one_group.get(0).getPlace().getPlace_name(), result.get(i).getRs());
}
model.addAttribute("searchResult", hashMap);
model.addAttribute("search", search);
ModelAndView modelAndView = new ModelAndView();
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
User user = userService.findUserByEmail(auth.getName());
modelAndView.addObject("currentUser", user);
modelAndView.addObject("fullName", "欢迎 " + user.getFullname());
modelAndView.addObject("adminMessage", "只有具有管理员权限的用户才能查看内容");
modelAndView.setViewName("searchResults");
return modelAndView;
}
}
配置类:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
@Autowired
CustomizeAuthenticationSuccessHandler customizeAuthenticationSuccessHandler;
@Bean
public UserDetailsService mongoUserDetails() {
return new CustomUserDetailsService();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
UserDetailsService userDetailsService = mongoUserDetails();
auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/login").permitAll()
.antMatchers("/signup").permitAll()
.antMatchers("/dashboard/**").hasAuthority("ADMIN").anyRequest()
.authenticated().and().csrf().disable().formLogin()
.successHandler(customizeAuthenticationSuccessHandler)
.loginPage("/login").failureUrl("/login?error=true")
.usernameParameter("email")
.passwordParameter("password")
.and().logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/").and().exceptionHandling();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/images/**");
}
}
如果您有任何疑问,请随时问我。
英文:
I have created a simple project using tutorials on Springboot
and mongodb
. Currently, I have a page like the following:
As you see, it is a search page. Til yesterday, it did not include the search option and the user could just click on login and then search for something
If the user clicks on the login
button and logs into the system, he can search for the items and the result is shown on a page called searchResults.html
without any problem.
However, what I need to do is to let the use search at the first page (the page has been changed to the picture shown above to include the search option) and see the results. That is, there are two options: 1) The user logs into the system, searches the items and see the results and 2) The user searches something without logging into the system.
The current implemention current the first part, but not the second part. I don't know how I should change my implementation.
Here is the relevant code (if I should share other parts of the code, please let me know):
First page code:
<body>
<div layout:fragment="content">
<h1>Welcome!</h1>
<form action="/search" method="POST">
<div class="form-group row">
<div class="col-sm-6" id="category_search">
<div class="dropdown">
<div class="input-group justify-content-center">
<div class="input-group-btn">
<button class="btn btn-md dropdown-toggle" type="button"
id="dropdownMenuButton" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false">Select a category</button>
<div class="dropdown-menu" onchange="selectMenu1"
aria-labelledby="dropdownMenuButton">
<a class="dropdown-item" href="#" data="Hotel">Hotel</a> <a
class="dropdown-item" href="#" data="Food">Fast food</a>
</div>
</div>
</div>
</div>
</div>
<div class="col-sm-3" id="search_city_id">
</div>
</div>
<div class="form-group row">
<div class="col-sm-3">
<input type="text" name="search" id="search"
class="form-control coloredInput" th:value="${search}" />
</div>
<button type="submit" class="btn btn-primary" value="search">Search</button>
</div>
</form>
</div>
</body>
</html>
Here is my controller class:
@Controller
public class RController {
@Autowired
private CustomUserDetailsService userService;
@RequestMapping("/home")
public String home(Model model) {
model.addAttribute("pointList", rRepository.findAll());
return "home";
}
@RequestMapping(value = "/search")
public ModelAndView search(Model model, @RequestParam("search") String search,
@RequestParam ("search-entityType-value") String searchEntityTypeValue,
@RequestParam("selected_category") String selected_category
) {
List<RAggrResults> result = RSearchRepository.searchRs(search, searchEntityTypeValue, selected_category);
LinkedHashMap<String, List<R>> hashMap = new LinkedHashMap<String, List<R>>();
for (int i = 0; i < result.size(); i++) {
List<R> rs_of_one_group = result.get(i).getRs();
hashMap.put(rs_of_one_group.get(0).getPlace().getPlace_name(), result.get(i).getRs());
}
model.addAttribute("searchResult", hashMap);
model.addAttribute("search", search);
ModelAndView modelAndView = new ModelAndView();
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
User user = userService.findUserByEmail(auth.getName());
modelAndView.addObject("currentUser", user);
modelAndView.addObject("fullName", "Welcome " + user.getFullname());
modelAndView.addObject("adminMessage", "Content Available Only for Users with Admin Role");
modelAndView.setViewName("searchResults");
return modelAndView;
}
}
And here is my configuration class:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
@Autowired
CustomizeAuthenticationSuccessHandler customizeAuthenticationSuccessHandler;
@Bean
public UserDetailsService mongoUserDetails() {
return new CustomUserDetailsService();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
UserDetailsService userDetailsService = mongoUserDetails();
auth
.userDetailsService(userDetailsService)
.passwordEncoder(bCryptPasswordEncoder);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/login").permitAll()
.antMatchers("/signup").permitAll()
.antMatchers("/dashboard/**").hasAuthority("ADMIN").anyRequest()
.authenticated().and().csrf().disable().formLogin().successHandler(customizeAuthenticationSuccessHandler)
.loginPage("/login").failureUrl("/login?error=true")
.usernameParameter("email")
.passwordParameter("password")
.and().logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/").and().exceptionHandling();
}
@Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/images/**");
}
}
Your help would be appreciated.
答案1
得分: 1
设置您的 /search
端点权限:.antMatchers("/search").permitAll()
。
其次,在您的情况下,我建议在将用户详细信息添加到视图之前,在控制器中检查用户是否已登录。
英文:
Set permition for your /search
endpoint: .antMatchers("/search").permitAll()
.
And secondly in your case I recommend to check if user is logged in in controller before you add user details to view.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论