gpt4 book ai didi

java - 使用 Vaadin 登录的 Spring Boot 安全性

转载 作者:搜寻专家 更新时间:2023-10-30 21:15:15 24 4
gpt4 key购买 nike

我尝试基于 Spring Boot (1.2.7.RELEASE) 和 Vaadin (7.6.3) 构建应用程序。我的问题是我无法将 Spring Security 与 Vaadin 集成。我想要一个自定义的 Vaadin 构建的 LoginScreen 和 Spring Security 控件。我的项目设置如下:

@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().
exceptionHandling().authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login")).accessDeniedPage("/accessDenied")
.and().authorizeRequests()
.antMatchers("/VAADIN/**", "/PUSH/**", "/UIDL/**", "/login", "/login/**", "/error/**", "/accessDenied/**", "/vaadinServlet/**").permitAll()
.antMatchers("/authorized", "/**").fullyAuthenticated();
}
}

这是我的 Vaadin 登录界面

 @SpringUI(path = "/login")
@Title("LoginPage")
@Theme("valo")
public class LoginUI extends UI {

TextField user;
PasswordField password;
Button loginButton = new Button("Login", this::loginButtonClick);
private static final String username = "username";
private static final String passwordValue = "test123";

@Override
protected void init(VaadinRequest request) {
setSizeFull();

user = new TextField("User:");
user.setWidth("300px");
user.setRequired(true);
user.setInputPrompt("Your username");

password = new PasswordField("Password:");
password.setWidth("300px");
password.setRequired(true);
password.setValue("");
password.setNullRepresentation("");

VerticalLayout fields = new VerticalLayout(user, password, loginButton);
fields.setCaption("Please login to access the application");
fields.setSpacing(true);
fields.setMargin(new MarginInfo(true, true, true, false));
fields.setSizeUndefined();

VerticalLayout uiLayout = new VerticalLayout(fields);
uiLayout.setSizeFull();
uiLayout.setComponentAlignment(fields, Alignment.MIDDLE_CENTER);
setStyleName(Reindeer.LAYOUT_BLUE);
setFocusedComponent(user);

setContent(uiLayout);
}

public void loginButtonClick(Button.ClickEvent e) {
//authorize/authenticate user
//tell spring that my user is authenticated and dispatch to my mainUI
}

}

当我启动我的应用程序时,spring 将我重定向到我的登录 UI,这很好。

但我不知道如何根据 spring 安全机制对用户进行身份验证并发送到我的 mainUI。

我也面临着 csrf token 的问题,如果我不禁用 csrf,我将得到 crfs token is null 异常。我找到了很多处理这些问题的示例,但是 Vaadin 没有提供解决方案。

感谢您的帮助。

最佳答案

经过一周的努力和研究,我终于可以正常工作了。非常累,因为网上有很多信息和解决方案,其中大部分使用基于 xml 的配置或基于 JSP 表单的登录,直到现在我找不到没有 xml 配置文件的解决方案,使用 Vaadin 框架创建一个自定义登录页面。

我不能保证这是最佳实践或最简单的解决方案。此外,我没有评估它的每个部分,登录机制就我所见有效,但可能存在一些我尚未发现的问题。

也许它会帮助面临同样问题的人,所以我会在这里发布我的答案。

首先是我的安全配置:

@Resource(name = "authService")
private UserDetailsService userDetailsService;

@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().
exceptionHandling().authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login")).accessDeniedPage("/accessDenied")
.and().authorizeRequests()
.antMatchers("/VAADIN/**", "/PUSH/**", "/UIDL/**", "/login", "/login/**", "/error/**", "/accessDenied/**", "/vaadinServlet/**").permitAll()
.antMatchers("/authorized", "/**").fullyAuthenticated();
}

@Bean
public DaoAuthenticationProvider createDaoAuthenticationProvider() {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();

provider.setUserDetailsService(userDetailsService);
provider.setPasswordEncoder(passwordEncoder());
return provider;
}

@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}

您必须禁用 crsf,但这没问题,因为 vaadin 有自己的 crsf 保护。

此外,您需要允许一些 URI,以便 vaadin 可以访问其资源:/VAADIN/** 是绝对必要的,我也建议允许 /vaadinServlet/**/PUSH/**/HEARTBEAT/**,但这取决于您使用的 Vaadin 的哪些部分。

第二个UserDetailsS​​ervice:

@Service("authService")
public class AuthService implements UserDetailsService {

@Autowired
CustomUserRepository userRepository;

@Override
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
CustomUser user = userRepository.findCustomUserByUserName(userName);

return user;
}

}

DaoAuthenticationProvider 使用 UserDetailsloadUserByUserName 方法获取实现了 UserDetails 的类的对象界面。请注意,UserDetailsInterface 中描述的每个属性都不能为 null,否则您稍后会收到 DaoAuthenticationProvider 抛出的 NullPointerException

我创建了一个实现 UserDetails 接口(interface)的 JPA 实体:

@Entity
public class CustomUser implements UserDetails {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
@ManyToMany(fetch = FetchType.EAGER)
Collection<Authorities> authorities;
String password;
String userName;
Boolean accountNonExpired;
Boolean accountNonLocked;
Boolean credentialsNonExpired;
Boolean enabled;

@Autowired
@Transient
BCryptPasswordEncoder passwordEncoder;

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}

@Override
public String getPassword() {
return password;
}

@Override
public String getUsername() {
return userName;
}

@Override
public boolean isAccountNonExpired() {
return accountNonExpired;
}

@Override
public boolean isAccountNonLocked() {
return accountNonLocked;
}

@Override
public boolean isCredentialsNonExpired() {
return credentialsNonExpired;
}

@Override
public boolean isEnabled() {
return enabled;
}

public void setId(Long id) {
this.id = id;
}

public void setAuthorities(Collection<Authorities> authorities) {
this.authorities = authorities;
}

public void setPassword(String password) {
this.password = passwordEncoder.encode(password);
}

public void setUserName(String userName) {
this.userName = userName;
}

public void setAccountNonExpired(Boolean accountNonExpired) {
this.accountNonExpired = accountNonExpired;
}

public void setAccountNonLocked(Boolean accountNonLocked) {
this.accountNonLocked = accountNonLocked;
}

public void setCredentialsNonExpired(Boolean credentialsNonExpired) {
this.credentialsNonExpired = credentialsNonExpired;
}

public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}

}

加上权威实体:

@Entity
public class Authorities implements GrantedAuthority {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;

String authority;

@Override
public String getAuthority() {
return authority;
}

public void setAuthority(String authority) {
this.authority = authority;
}

}

显然,在身份验证生效之前,您必须先将一些用户数据存储在数据库中。

在 Vaadin 中,我无法通过使用具有不同 View 的一个 UI 来实现它,所以我最终使用了两个 UI,一个用于登录,另一个用于主应用程序。

在 Vaadin 中,我可以在类注释中设置 URI 路径:

@SpringUI(path = "/login")
@Title("LoginPage")
@Theme("valo")
public class LoginUI extends UI {
//...
}

使用此配置,我的登录屏幕在 localhost:port/login 可用我的主要应用程序位于 localhost:port/main

我在 loginUI 的 button.click 方法中以编程方式登录用户:

Authentication auth = new UsernamePasswordAuthenticationToken(userName.getValue(),password.getValue());
Authentication authenticated = daoAuthenticationProvider.authenticate(auth);
SecurityContextHolder.getContext().setAuthentication(authenticated);

//redirect to main application
getPage().setLocation("/main");

希望对大家有所帮助。

关于java - 使用 Vaadin 登录的 Spring Boot 安全性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35912404/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com