springboot项目中java代码如何获取head中的token
时间: 2024-02-09 13:09:17 浏览: 147
在Spring Boot项目中,可以通过HttpServletRequest对象获取HTTP请求的头部信息,包括token。具体代码如下:
```java
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TokenController {
@GetMapping("/token")
public String getToken(HttpServletRequest request) {
String token = request.getHeader("token");
return token;
}
}
```
在上述代码中,我们定义了一个RestController,其中包含一个获取Token的接口。该接口的实现方式是通过HttpServletRequest对象获取请求头中的token信息。在代码中,我们使用了`request.getHeader("token")`方法来获取token信息。
相关问题
springboot shiro 单点登录代码
以下是一个简单的 Spring Boot 应用程序,使用 Apache Shiro 实现单点登录功能:
1. 配置 pom.xml 文件,添加以下依赖:
```xml
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring-boot-web-starter</artifactId>
<version>1.4.2</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.4.2</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>1.4.2</version>
</dependency>
```
2. 编写 Shiro 配置类,例如:
```java
@Configuration
public class ShiroConfig {
@Bean
public SecurityManager securityManager() {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(realm());
return securityManager;
}
@Bean
public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
shiroFilter.setSecurityManager(securityManager);
shiroFilter.setLoginUrl("/login");
shiroFilter.setSuccessUrl("/index");
shiroFilter.setUnauthorizedUrl("/403");
Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
filterChainDefinitionMap.put("/logout", "logout");
filterChainDefinitionMap.put("/static/**", "anon");
filterChainDefinitionMap.put("/login", "anon");
filterChainDefinitionMap.put("/sso_login", "anon");
filterChainDefinitionMap.put("/**", "authc");
shiroFilter.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilter;
}
@Bean
public ShiroRealm realm() {
ShiroRealm realm = new ShiroRealm();
realm.setCredentialsMatcher(hashedCredentialsMatcher());
return realm;
}
@Bean
public HashedCredentialsMatcher hashedCredentialsMatcher() {
HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
credentialsMatcher.setHashAlgorithmName("SHA-256");
credentialsMatcher.setHashIterations(2);
return credentialsMatcher;
}
@Bean
public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
return new LifecycleBeanPostProcessor();
}
@Bean
public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
defaultAdvisorAutoProxyCreator.setProxyTargetClass(true);
return defaultAdvisorAutoProxyCreator;
}
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
advisor.setSecurityManager(securityManager);
return advisor;
}
}
```
3. 编写 ShiroRealm 类,例如:
```java
public class ShiroRealm extends AuthorizingRealm {
@Autowired
private UserService userService;
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
User user = (User) principals.getPrimaryPrincipal();
authorizationInfo.setRoles(user.getRoles());
authorizationInfo.setStringPermissions(user.getPermissions());
return authorizationInfo;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
UsernamePasswordToken upToken = (UsernamePasswordToken) token;
String username = upToken.getUsername();
User user = userService.findByUsername(username);
if (user == null) {
throw new UnknownAccountException("用户不存在");
}
SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user, user.getPassword(), getName());
return authenticationInfo;
}
}
```
4. 编写登录页面和登录控制器,例如:
登录页面:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<form action="/sso_login" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username">
<br>
<label for="password">Password:</label>
<input type="password" id="password" name="password">
<br>
<input type="submit" value="Login">
</form>
</body>
</html>
```
登录控制器:
```java
@Controller
public class LoginController {
@Autowired
private UserService userService;
@GetMapping("/login")
public String login() {
return "login";
}
@PostMapping("/sso_login")
public String ssoLogin(String username, String password, HttpServletRequest request, HttpServletResponse response) {
User user = userService.findByUsername(username);
if (user == null) {
throw new UnknownAccountException("用户不存在");
}
String hashedPassword = new Sha256Hash(password, user.getSalt(), 2).toString();
if (!hashedPassword.equals(user.getPassword())) {
throw new IncorrectCredentialsException("密码错误");
}
Subject subject = SecurityUtils.getSubject();
subject.login(new UsernamePasswordToken(username, password));
String sessionId = subject.getSession().getId().toString();
Cookie cookie = new Cookie("JSESSIONID", sessionId);
cookie.setPath("/");
response.addCookie(cookie);
return "redirect:/index";
}
@GetMapping("/index")
public String index() {
return "index";
}
@GetMapping("/logout")
public String logout() {
Subject subject = SecurityUtils.getSubject();
subject.logout();
return "redirect:/login";
}
@GetMapping("/403")
public String forbidden() {
return "403";
}
}
```
5. 启动应用程序并访问登录页面,输入用户名和密码,登录成功后可以访问受保护的页面,如果有多个应用程序需要实现单点登录,只需在每个应用程序中实现相同的 Shiro 配置和登录控制器即可。
springboot整合springsecurity+oauth2.0实现token认证
嗨!关于Spring Boot整合Spring Security和OAuth2.0实现token认证,你可以按照以下步骤进行操作:
1. 添加依赖:在你的Spring Boot项目的pom.xml文件中,添加Spring Security和OAuth2.0相关的依赖。
```xml
<dependencies>
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- Spring Security OAuth2 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
</dependencies>
```
2. 配置Spring Security:创建一个继承自WebSecurityConfigurerAdapter的配置类,并重写configure方法来配置Spring Security的行为。
```java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/oauth2/**", "/login/**", "/logout/**")
.permitAll()
.anyRequest()
.authenticated()
.and()
.oauth2Login()
.loginPage("/login")
.and()
.logout()
.logoutSuccessUrl("/")
.invalidateHttpSession(true)
.clearAuthentication(true)
.deleteCookies("JSESSIONID");
}
}
```
在上述配置中,我们允许访问一些特定的URL(如/oauth2/**,/login/**和/logout/**),并保护所有其他URL。我们还设置了自定义的登录页面和注销成功后的跳转页面。
3. 配置OAuth2.0:创建一个继承自AuthorizationServerConfigurerAdapter的配置类,并重写configure方法来配置OAuth2.0的行为。
```java
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients
.inMemory()
.withClient("client_id")
.secret("client_secret")
.authorizedGrantTypes("authorization_code", "password", "refresh_token")
.scopes("read", "write")
.accessTokenValiditySeconds(3600)
.refreshTokenValiditySeconds(86400);
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints
.authenticationManager(authenticationManager);
}
}
```
在上述配置中,我们使用内存存储客户端信息(client_id和client_secret),并配置了授权类型(如authorization_code、password和refresh_token)。我们还设置了访问令牌和刷新令牌的有效期。
4. 创建登录页面:创建一个HTML登录页面,用于用户进行身份验证并获取访问令牌。
```html
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<h2>Login</h2>
<form th:action="@{/login}" method="post">
<div>
<label for="username">Username:</label>
<input type="text" id="username" name="username" />
</div>
<div>
<label for="password">Password:</label>
<input type="password" id="password" name="password" />
</div>
<div>
<button type="submit">Login</button>
</div>
</form>
</body>
</html>
```
5. 处理登录请求:创建一个控制器来处理登录请求,并在登录成功后重定向到受保护的资源。
```java
@Controller
public class LoginController {
@GetMapping("/login")
public String showLoginForm() {
return "login";
}
@PostMapping("/login")
public String loginSuccess() {
return "redirect:/protected-resource";
}
}
```
在上述控制器中,我们使用@GetMapping注解来处理GET请求,@PostMapping注解来处理POST请求。登录成功后,我们将用户重定向到受保护的资源。
这样,你就完成了Spring Boot整合Spring Security和OAuth2.0实现token认证的配置。你可以根据自己的需求进行进一步的定制和扩展。希望对你有所帮助!如果你有任何疑问,请随时问我。
阅读全文