如何在有和没有Spring Boot身份验证的情况下访问页面?

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

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:
如何在有和没有Spring Boot身份验证的情况下访问页面?

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:

    &lt;body&gt;
&lt;div layout:fragment=&quot;content&quot;&gt;
&lt;h1&gt;Welcome!&lt;/h1&gt;
&lt;form action=&quot;/search&quot; method=&quot;POST&quot;&gt;
&lt;div class=&quot;form-group row&quot;&gt;
&lt;div class=&quot;col-sm-6&quot; id=&quot;category_search&quot;&gt;
&lt;div class=&quot;dropdown&quot;&gt;
&lt;div class=&quot;input-group justify-content-center&quot;&gt;
&lt;div class=&quot;input-group-btn&quot;&gt;
&lt;button class=&quot;btn btn-md dropdown-toggle&quot; type=&quot;button&quot;
id=&quot;dropdownMenuButton&quot; data-toggle=&quot;dropdown&quot;
aria-haspopup=&quot;true&quot; aria-expanded=&quot;false&quot;&gt;Select a category&lt;/button&gt;
&lt;div class=&quot;dropdown-menu&quot; onchange=&quot;selectMenu1&quot;
aria-labelledby=&quot;dropdownMenuButton&quot;&gt;
&lt;a class=&quot;dropdown-item&quot; href=&quot;#&quot; data=&quot;Hotel&quot;&gt;Hotel&lt;/a&gt; &lt;a
class=&quot;dropdown-item&quot; href=&quot;#&quot; data=&quot;Food&quot;&gt;Fast food&lt;/a&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;col-sm-3&quot; id=&quot;search_city_id&quot;&gt;
&lt;/div&gt;  
&lt;/div&gt;   
&lt;div class=&quot;form-group row&quot;&gt;   
&lt;div class=&quot;col-sm-3&quot;&gt;
&lt;input type=&quot;text&quot; name=&quot;search&quot; id=&quot;search&quot;
class=&quot;form-control coloredInput&quot; th:value=&quot;${search}&quot; /&gt;
&lt;/div&gt;
&lt;button type=&quot;submit&quot; class=&quot;btn btn-primary&quot; value=&quot;search&quot;&gt;Search&lt;/button&gt;
&lt;/div&gt;    
&lt;/form&gt;   
&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;

Here is my controller class:

@Controller
public class RController {
@Autowired
private CustomUserDetailsService userService;
@RequestMapping(&quot;/home&quot;)
public String home(Model model) {
model.addAttribute(&quot;pointList&quot;, rRepository.findAll());
return &quot;home&quot;;
}
@RequestMapping(value = &quot;/search&quot;)
public ModelAndView search(Model model, @RequestParam(&quot;search&quot;) String search,
@RequestParam (&quot;search-entityType-value&quot;) String searchEntityTypeValue,
@RequestParam(&quot;selected_category&quot;) String selected_category
) {
List&lt;RAggrResults&gt; result = RSearchRepository.searchRs(search, searchEntityTypeValue, selected_category);
LinkedHashMap&lt;String, List&lt;R&gt;&gt; hashMap = new LinkedHashMap&lt;String, List&lt;R&gt;&gt;();
for (int i = 0; i &lt; result.size(); i++) {
List&lt;R&gt; 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(&quot;searchResult&quot;, hashMap);
model.addAttribute(&quot;search&quot;, search);
ModelAndView modelAndView = new ModelAndView();
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
User user = userService.findUserByEmail(auth.getName());
modelAndView.addObject(&quot;currentUser&quot;, user);
modelAndView.addObject(&quot;fullName&quot;, &quot;Welcome &quot; + user.getFullname());
modelAndView.addObject(&quot;adminMessage&quot;, &quot;Content Available Only for Users with Admin Role&quot;);
modelAndView.setViewName(&quot;searchResults&quot;);
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(&quot;/&quot;).permitAll()
.antMatchers(&quot;/login&quot;).permitAll()
.antMatchers(&quot;/signup&quot;).permitAll()
.antMatchers(&quot;/dashboard/**&quot;).hasAuthority(&quot;ADMIN&quot;).anyRequest()
.authenticated().and().csrf().disable().formLogin().successHandler(customizeAuthenticationSuccessHandler)
.loginPage(&quot;/login&quot;).failureUrl(&quot;/login?error=true&quot;)
.usernameParameter(&quot;email&quot;)
.passwordParameter(&quot;password&quot;)
.and().logout()
.logoutRequestMatcher(new AntPathRequestMatcher(&quot;/logout&quot;))
.logoutSuccessUrl(&quot;/&quot;).and().exceptionHandling();
}
@Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers(&quot;/resources/**&quot;, &quot;/static/**&quot;, &quot;/css/**&quot;, &quot;/js/**&quot;, &quot;/images/**&quot;);
}
}

Your help would be appreciated.

答案1

得分: 1

设置您的 /search 端点权限:.antMatchers("/search").permitAll()
其次,在您的情况下,我建议在将用户详细信息添加到视图之前,在控制器中检查用户是否已登录。

英文:

Set permition for your /search endpoint: .antMatchers(&quot;/search&quot;).permitAll().
And secondly in your case I recommend to check if user is logged in in controller before you add user details to view.

huangapple
  • 本文由 发表于 2020年9月4日 23:57:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/63744458.html
匿名

发表评论

匿名网友

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

确定