我尝试使用spring security进行登录,但它不起作用,因为它返回给我这个链接:http://localhost:8080/login?error并在主页上报告我:这是代码:
静态页面中的一个索引,它重新链接我:
<a href="login">LogIn</a>
在模板中,我有以下内容:
<h2>Digita il tuo username e la tua password per accedere al sistema </h2>
<form th:action="@{/login}" method="post" th:object="${responsabile}">
<div class="field half first">
<label for="name"><span class="icon fa-user"></span>Username:</label>
<input name="name" id="username" type="text" placeholder="Username" th:field="*{nomeUtente}"/>
</div>
<div class="field half">
<label for="email"><span class="icon fa-code"></span> Password:</label>
<input name="email" id="email" type="password" placeholder="Password" th:field="*{chiaveAccesso}"/>
</div>
<ul class="actions">
<li><input value="Login" class="button" type="submit"/></li>
</ul>
</form>
并且捕获它的请求映射就在那里:
package it.uniroma3.controller;
import it.uniroma3.model.Centro;
import it.uniroma3.model.Responsabile;
import it.uniroma3.service.CentroService;
import it.uniroma3.service.ResponsabileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import javax.html" target="_blank">servlet.http.HttpSession;
import javax.validation.Valid;
@Controller
public class LoginController {
@Autowired
private ResponsabileService responsabileService;
@Autowired
private CentroService centroService;
@RequestMapping("/login")
public String login(Model model) {
model.addAttribute("responsabile", new Responsabile());
return "login";
}
@RequestMapping("/role")
public String loginRole(HttpSession session, Model model) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String role = auth.getAuthorities().toString();
Responsabile responsabile = this.responsabileService.findByNomeUtente(auth.getName());
String targetUrl = "";
if(role.contains("RESPONSABILE")) {
session.setAttribute("responsabile", responsabile);
Centro centro=this.centroService.findById(responsabile.getCentro().getId());
session.setAttribute("centro", centro);
model.addAttribute("username",responsabile.getNomeUtente());
targetUrl = "/responsabile/respPanel";
} else if(role.contains("DIRETTORE")) {
session.setAttribute("responsabile", responsabile);
model.addAttribute("username", responsabile.getNomeUtente());
targetUrl = "/direttore/direttorePanel";
}
return targetUrl;
}
}
@Entity
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
@Column(nullable=false)
private String nome;
@Column(nullable=false)
private String cognome;
@Column(nullable=false, unique=true)
private String nomeUtente;
@Column(nullable=false)
private String chiaveAccesso;
@ManyToOne //ok
private Azienda azienda;
@OneToOne //ok
private Azienda aziendadiretta;
@OneToOne(cascade=CascadeType.ALL)
private Centro centro;
@Column(nullable=false)
private String role;
package it.uniroma3.error;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
// handle 403 page
@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {
private static Logger logger = LoggerFactory.getLogger(MyAccessDeniedHandler.class);
@Override
public void handle(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
AccessDeniedException e) throws IOException, ServletException {
Authentication auth
= SecurityContextHolder.getContext().getAuthentication();
if (auth != null) {
logger.info("User '" + auth.getName()
+ "' attempted to access the protected URL: "
+ httpServletRequest.getRequestURI());
}
httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/403");
}
}
package it.uniroma3.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.access.AccessDeniedHandler;
import javax.sql.DataSource;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final String usersQuery = "SELECT nome_utente,chiave_accesso,TRUE FROM responsabile WHERE nome_utente = ?";
private final String rolesQuery = "SELECT nome_utente,role FROM responsabile WHERE nome_utente = ?";
@Qualifier("dataSource")
@Autowired
private DataSource dataSource;
@Autowired
private AccessDeniedHandler accessDeniedHandler;
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource)
.passwordEncoder(new BCryptPasswordEncoder())
.usersByUsernameQuery(usersQuery)
.authoritiesByUsernameQuery(rolesQuery);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/", "/index", "/login").permitAll()
.antMatchers("/**").hasRole("DIRETTORE")
.antMatchers("/**").hasRole("RESPONSABILE")
.anyRequest().permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/role")
.and()
.logout()
.logoutSuccessUrl("/login")
.permitAll()
.and()
.exceptionHandling().accessDeniedHandler(accessDeniedHandler);
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource)
.passwordEncoder(bCryptPasswordEncoder())
.usersByUsernameQuery(usersQuery)
.authoritiesByUsernameQuery(rolesQuery);
}
//Spring Boot configured this already.
@Override
public void configure(WebSecurity web) {
web
.ignoring()
.antMatchers("/static/**","/assets/**","/images/**" );
}
/*
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("superadmin").password("superadmin").roles("SUPERADMIN");
}
*/
}
日志:在6.958秒内启动了ProgettoSiwApplication(JVM运行7.964)2018-06-21 12:55:36.453信息13584---[nio-8080-exec-1]O.A.C.C.C.[Tomcat].[localhost].[/]:初始化Spring FrameworkServlet“Dispatcher Servlet”2018-06-21 12:55:36.453信息13584---[nio-8080-exec-1]O.s.web.servlet.DispatcherServlet:FrameworkServlet“Dispatcher Servlet”:初始化启动2018-06-21 12:55:36.487信息13584---
请将安全配置类更改为。
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/role")
.permitAll()
.and()
.logout()
.permitAll();
}
@Bean
@Override
public UserDetailsService userDetailsService() {
UserDetails user =
User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.roles("USER")
.build();
return new InMemoryUserDetailsManager(user);
}
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Spring Security Example </title>
</head>
<body>
<!--<div th:if="${param.error}">
Invalid username and password.
</div>
<div th:if="${param.logout}">
You have been logged out.
</div>-->
<form th:action="@{/login}" method="post">
<div><label> User Name : <input type="text" name="username"/> </label></div>
<div><label> Password: <input type="password" name="password"/> </label></div>
<div><input type="submit" value="Sign In"/></div>
</form>
</body>
</html>
在此查找工作代码https://gitlab.com/supun/spring-boot-app/commit/be2f0f723f5aec728bcaf777325fb1899d878f8f
首先,我想让你知道,我是新来的Symfony。我在路上把我的PHP项目从我自己的“基本”MVC转到SimfOn.该项目已经运行良好,但我在适应Symfony时遇到了一些问题。 我从基本的框架开始,make: user和make: auth。模板运行良好。但是我未能将登录过程转换为AJAX和JSON。 我遵循了这个官方教程:https://symfonycasts.com/screencast/ap
springsecurity oauth2.0 谁做过记录登录日志?监听事件好像没法区分是什么原因失败的、比如client错误还是用户名错误
我正在Java创建一个管理系统。 我有这个登录表。与数据库的连接看起来很好,因为它没有给出错误。 但是当我尝试执行try{}和catch{}时,它给出了一个错误。 我希望有谁能帮助我。 它总是给出: catch(Exception ex){JoptionPane.ShowMessageDialog(null,“登录操作错误”,“登录错误”,JoptionPane.Error_Message);}
我有一个登记表,它可以注册和登录用户。我使用
我得到了一个登录表单,提交后,但似乎不自动认证,我可以看到匿名在分析器,即使我登录为管理员。 我正在从数据库中获取数据: 当然,数据库中存储的密码是加密的。 security.yml(app/config/security.yml) SecurityController.php(src/AppBundle/Controller) User.php(src/AppBundle/Entity/User
目前,我正在使用以下内容将用户登录到我的应用程序中。然而,我想使用一个角函数来实际执行登录。为此,我想创建一个Rest网络服务来进行身份验证,但是我在SO上看到的所有示例都使用我认为被贬低的用户。我还希望该服务返回有关用户的信息。 我要问的是如何将MyUserDetailsService更改为用作登录的restful服务,或者如何创建一个可用于登录的服务,该服务将在登录后返回用户对象。 这是我的a