安卓之使用BASIC AUTH进行登录验证

本文介绍如何在Android应用中实现BASIC AUTH登录验证,通过UsernamePasswordCredentials、AuthScope和BasicCredentialsProvider类完成论坛客户端的OAUTH验证系统集成。
摘要由CSDN通过智能技术生成

	public String Get(String netUrl,String usr,String psw){
		
	
		URL url = new URL(netUrl);
		UsernamePasswordCredentials upc = new UsernamePasswordCredentials(usr,psw);  //这一句使用用户名密码建立了一个数据
		AuthScope as = new AuthScope(null,-1);
		
		BasicCredentialsProvider bcp = new BasicCredentialsProvider();   //下面这一段我是抄的=。= 
		bcp.setCredentials(as, upc);
		
		DefaultHttpClient dhc= new DefaultHttpClient();
		dhc.setCredentialsProvider(bcp);   //给client设置了一个验证身份的部分
                /*-------------------------分割线---------------------------------*/
		
		HttpGet hg= new HttpGet(netUrl);
		HttpResponse hr=null;
		hr = dhc.execute(hg);
		
		String line=null;
		StringBuilder builder = new StringBuilder();
		BufferedReader reader=null;
		reader = new BufferedReader(new InputStreamReader(hr.getEntity().getContent() ));  //获取数据
				
		while((line = reader.readLine()) != null) builder.append(line);

		
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个完整的基于Gin框架的基本身份验证流程的代码示例: ```go package main import ( "github.com/gin-gonic/gin" "net/http" ) func main() { router := gin.Default() // 定义一个验证函数 auth := func(username, password string) bool { // 这里可以根据具体需求进行用户名和密码的验证 return username == "admin" && password == "password" } // 使用BasicAuth中间件,并提供验证函数 router.Use(gin.BasicAuth(gin.Accounts{ "admin": "password", })) // 受保护的路由 router.GET("/protected", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"message": "Access granted"}) }) router.Run(":8080") } ``` 在上述代码中,我们首先创建了一个Gin的路由实例。然后,我们定义了一个验证函数`auth`,该函数根据用户名和密码进行身份验证。 接下来,我们使用`gin.BasicAuth`中间件,并为其提供一个包含预定义用户名和密码的映射。这些用户名和密码将用于验证过程。 然后,我们定义了一个受保护的路由`/protected`,当用户访问该路由时,中间件将自动调用验证函数进行身份验证。如果身份验证成功,将返回一个HTTP 200 OK的响应,消息为"Access granted"。 对于前端应用程序,要发送认证请求,可以使用JavaScript的fetch函数或者Axios库发送HTTP请求,并在请求头中包含基本身份验证信息。 以下是使用fetch函数发送认证请求的示例代码: ```javascript const username = 'admin'; const password = 'password'; const url = 'http://localhost:8080/protected'; const authHeader = 'Basic ' + btoa(username + ':' + password); fetch(url, { headers: { 'Authorization': authHeader } }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error)); ``` 在上述示例中,我们首先定义了用户名和密码,并指定要访问的URL。然后,我们创建一个认证头信息,将用户名和密码进行Base64编码,并使用`Basic`前缀拼接。 最后,我们使用fetch函数发送HTTP请求,并在请求头中添加认证头信息。服务器将使用Gin的`BasicAuth`中间件进行身份验证,并根据提供的用户名和密码返回相应的响应。 请注意,上述示例中的代码是使用纯JavaScript进行发送认证请求的示例。对于其他前端框架或库,例如React、Vue或Angular,也可以使用类似的方式发送认证请求,只需将认证头信息添加到相应的HTTP请求头中即可。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值